<?php
require "racs.php";
require "vtshowsBBB.php";
session_start();
if(!isset($_SESSION['titles']) || !isset($_SESSION['positions'])|| !isset($_SESSION['usernames'])){
header("location:index.php");}
?>
<html>
<title>Invoice Upload</title>
<head>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script src="datesps.js"></script>
<link rel="stylesheet" type="text/css" href="vtxstyles.css">

<?php
if(isset($_REQUEST['file_submit'])){
$csvf=$_FILES['files']['tmp_name'];
update_invoices(0,$csvf);
}

function update_invoices($acl,$fl)
{
set_time_limit(0);

$conn=mysqli_connect("localhost","primarysales","S5L7lF01EQZvQrGK","primarysales_dianaold");
$cols=0;
$rows=0;
$state=0;
$unos=0;

$csvf=$fl;

if(strlen($fl)>2){
printf("%s<br>",$csvf);

$cols=0;
$rows=0;
$state=0;
$unos=0;

if (($handle = fopen($csvf, "r")) != FALSE) {
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
$rows++;

if(strlen($data[2])>0 && strlen($data[6])>0 && $rows>=0){
$adstate=1;
$state=0;
$dates=0;

$arr=explode("/",$data[3]);
if(count($arr)>1){
$dates=$arr[2]."-".$arr[1]."-".$arr[0];
}

$agent = $data[6];
$invoice = $data[2];
$companycode = $data[26];
$invoiceNumber = $companycode . '-' . $invoice;
$voucherr = $data[16];
$values = ($data[12] + $data[13]) - $rst[10];

$netvalues = $data[13];
$disrates = ($data[11] / 100) * -1;
$disvall = $data[12] * -1;

if (strlen($data[10]) > 0) {
    // Check for potential division by zero
    if ($values != 0) {
        $vatrate = $data[10] / $values;
    } else {
        $vatrate = 0;
    }
} else {
    $vatrate = 0;
}



}


if($data[2]!='Totals'){
$unos++; // Increment the $unos variable

// Assign and trim values from the $data array
$items = $data[18];
$qty = $data[20];
$prices = $data[23];
$mrprice = $data[30];
$itemcode = trim($data[18]);
$listprice = (float) $data[29];
$inlistp = (float) $data[27];
$um = (int) $data[28];
$pqty = (int) $data[21]; // Initialize $pqty


// Ensure $um is not zero to avoid division by zero error
if ($um == 0) {
    echo "Error: 'um' cannot be zero.";
    exit;
}

// Calculate box price and box quantity
$bxprice = $inlistp * $um;
$bqty = $pqty / $um;

// Concatenate item code with the result of listprice multiplied by um
$calculated_value = $listprice * $um;
$uncode = $itemcode . $calculated_value;

//echo $uncode;
//13/14
$sqlst="select zone,region, rsm_name, executive_name, rep_name, agent_name, agent_type, territory_name,zone_order,sub_region,chanelname,range_type,arm_name,sm_id,rm_id,asm_name from agentsmrdcho where sap_code='".$agent."'";
$aqry=mysqli_query($conn,$sqlst);
if(mysqli_num_rows($aqry)==0){
printf("following agents do not exist - %s<br>",$agent);}
$rsta=mysqli_fetch_row($aqry);

//WHERE CONCAT(sap_itcode, whole_sale_price) = '".$uncode."'";
$rsqlst = "SELECT DISTINCT item_name, item_ranges, sub_ranges, (packets_per_box * pcs_per_packet) AS total_pcs, packet_weight, location, itemcode 
FROM itemsmrd WHERE CONCAT(sap_itcode, whole_sale_price) = '".$uncode."'";

$rqry=mysqli_query($conn,$rsqlst);
if(mysqli_num_rows($rqry)==0){
printf("following items do not exist - %s<br>",$items);}

$trst=mysqli_fetch_row($rqry);
$itmnemee=$trst[0];
$itemranges=$trst[1];
$subranges=$trst[2];
$packetsperbox=$trst[3];
$packetweights=$trst[4];
$storeloc=$trst[5];
$itemcoded=$trst[6];

$marginrates=0;

$vsqlst="insert into rc_invoices(dates,sale_types,invoice_types,invoice_number,voucher_number,naration,agent_names,agent_types,zone_orders,zones,regions,chanell,sub_regions,rsm_names,executive_names,territory_names,range_types,arm_names,sm_id,rm_id,asm_names,rep_names, ";
$vsqlst=$vsqlst." item_names,item_ranges,sub_ranges,packets_per_box,packet_weights,box_price,box_qty,discount_values, ";
$vsqlst=$vsqlst."grand_values,net_values,user_names,discount_rates,margin_rates,paymode,itemcodes,vat_rates,box_mrp,payments,user_dates) values ('";
$vsqlst=$vsqlst.$dates."','Primary invoice','Primary Invoice','".$invoiceNumber."','".$voucherr."','".$naration."','".$rsta[5]."','".$rsta[6]."','".$rsta[8]."','".$rsta[0]."','".$rsta[1]."','".$rsta[10]."','".$rsta[9]."','".$rsta[2]."','".$rsta[3]."','".$rsta[7]."','".$rsta[11]."','".$rsta[12]."','".$rsta[13]."','".$rsta[14]."','".$rsta[15]."','".$rsta[4];
$vsqlst=$vsqlst."','".$itmnemee."','".$itemranges."','".$subranges."',".$packetsperbox.",".$packetweights.",".$bxprice.",".$bqty.",".$disvall.",".$values.",".$netvalues;
$vsqlst=$vsqlst.",'test user','".$disrates."','".$marginrates."','".$paymode."','".$itemcoded."','".$vatrate."','".$mrprice."','NOT DELIVERD',now())";
$aqry=mysqli_query($conn,$vsqlst);
}
}
}
}

printf("<div class='cmp'>");
printf("Upload complete<br>Total invoices uploaded - %s<br>",$unos);
printf("</div>");
}
?>
<link rel="stylesheet" tupe"text/css" href="rdsty.css">
</head>
<body style="font-family:calibri;font-size:small" onload="mnh('amnc','agentsb')">
</body>
</html>

<?php
$dates=0;
$months=date('m');
$days=date('t');
$years=date('Y');
if($dates==0 || $dates==''){
$dates=$years."-".$months."-01";}
$starts=$years."-".$months."-01";
$ends=$years."-".$months."-".$days;

stps(1);
printf("<div class='sds'>");
newdash(1);
printf("</div>");

printf("<div class='mnf'>");
printf("<b>Import Order Invoices form from Tally system<br></b>");
printf("The file type should be CSV. Export in detailed view with codes<br><br>");
printf("Select the file:");
printf("<form  enctype='multipart/form-data' method='POST' action='pruploadcho.php?actp=0'>");
printf("<input type='file' id='files' name='files' ><br><br>");
printf("<input type='submit' name='file_submit' value='Go' ><br>");
printf("</form>");
?>
</body>
</html>
