<?php
require "salesstyles.php";
require "showshp.php";
session_start();
if (!isset($_SESSION['titles']) || !isset($_SESSION['positions']) || !isset($_SESSION['usernames'])) {
    header("location:index.php");
    exit();
}

function update_invoices($acl, $fl)
{
    set_time_limit(0);
    $conn = mysqli_connect("localhost", "primarysales", "S5L7lF01EQZvQrGK", "primarysales_diana");

    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $csvf = $fl;
    $unos = 0;

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

        if (($handle = fopen($csvf, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
                if (strlen($data[0]) > 0 && strlen($data[2]) > 0) {
                    $arr = explode("/", $data[0]);
                    $dates = (count($arr) > 1) ? $arr[2] . "-" . $arr[1] . "-" . $arr[0] : '';
                    $agents = $data[1];
                    $items = $data[2];
                    $prices = $data[3];
                    $qtys = $data[4];
                    $routt = $data[5];

                    $sqlst = "SELECT zone, region, rsm_name, executive_name, rep_name, agent_type, territory_name, chanelname, range_type, zone_order, sub_region, agent_name, arm_name,sm_id,rm_id,asm_name FROM agentsmrd WHERE agent_name='" . mysqli_real_escape_string($conn, $agents) . "'";
                    $aqry = mysqli_query($conn, $sqlst);

                    if (mysqli_num_rows($aqry) == 0) {
                        printf("Following agents do not exist - %s<br>", htmlspecialchars($data[1]));
                    } else {
                        $rsta = mysqli_fetch_row($aqry);
                        $zones = $rsta[0];
                        $regions = $rsta[1];
                        $rsms = $rsta[2];
                        $executives = $rsta[3];
                        $reps = $rsta[4];
                        $agenttypes = $rsta[5];
                        $chnl = $rsta[7];
                        $territorys = $rsta[6];
                        $micmac = $rsta[8];
                        $zord = $rsta[9];
                        $subrgn = $rsta[10];
                        $agnm = $rsta[11];
                        $arm = $rsta[12];
                        $smid = $rsta[13];
                        $rmid = $rsta[14];
                        $asmn = $rsta[15];

                        $rsqlst = "SELECT DISTINCT item_name, item_ranges, sub_ranges, (packets_per_box*pcs_per_packet), packet_weight FROM itemsmrd WHERE itemcode='" . mysqli_real_escape_string($conn, $items) . "'";
                        $rqry = mysqli_query($conn, $rsqlst);

                        if (mysqli_num_rows($rqry) == 0) {
                            printf("Following items do not exist - %s<br>", htmlspecialchars($items));
                        } else {
                            $trst = mysqli_fetch_row($rqry);
                            $itemnm = $trst[0];
                            $itemranges = $trst[1];
                            $subranges = $trst[2];
                            $packetsperbox = $trst[3];
                            $packetweights = $trst[4];

                            $vsqlst = "INSERT INTO rd_saleinv (dates, invoice_types, invoice_number, agent_names, arm_names,sm_id,rm_id,asm_names,sub_regions,chanell, agent_types, zones, regions, rsm_names, executive_names, sfa_ref, territory_names, range_types, zone_orders, item_names, item_ranges, sub_ranges, packets_per_box, pcs_price, pcs_qty, grand_values, packet_weights, user_names, routes, itemcodes, user_dates) 
                                       VALUES ('" . mysqli_real_escape_string($conn, $dates) . "', 'RD day sales', '240100', '" . mysqli_real_escape_string($conn, $agnm) . "', '" . mysqli_real_escape_string($conn, $arm) . "', '" . mysqli_real_escape_string($conn, $smid) . "', '" . mysqli_real_escape_string($conn, $rmid) . "', '" . mysqli_real_escape_string($conn, $asmn) . "', '" . mysqli_real_escape_string($conn, $subrgn) . "', '" . mysqli_real_escape_string($conn, $chnl) . "', '" . mysqli_real_escape_string($conn, $agenttypes) . "', '" . mysqli_real_escape_string($conn, $zones) . "', '" . mysqli_real_escape_string($conn, $regions) . "', '" . mysqli_real_escape_string($conn, $rsms) . "', '" . mysqli_real_escape_string($conn, $executives) . "', 'Nov17', '" . mysqli_real_escape_string($conn, $territorys) . "', '" . mysqli_real_escape_string($conn, $micmac) . "', '" . mysqli_real_escape_string($conn, $zord) . "', '" . mysqli_real_escape_string($conn, $itemnm) . "', '" . mysqli_real_escape_string($conn, $itemranges) . "', '" . mysqli_real_escape_string($conn, $subranges) . "', $packetsperbox, $prices, $qtys, " . ($qtys * $prices) . ", $packetweights, 'vashii', '" . mysqli_real_escape_string($conn, $routt) . "', '" . mysqli_real_escape_string($conn, $items) . "', NOW())";

                            if (mysqli_query($conn, $vsqlst) === FALSE) {
                                echo "Error: " . htmlspecialchars($vsqlst) . "<br>" . mysqli_error($conn);
                            } else {
                                $unos++;
                            }
                        }
                    }
                }
            }
            fclose($handle);
        }
    }

    printf("<div class='cmp'>");
    printf("Upload complete<br>Total invoices uploaded - %s<br>", $unos);
    printf("</div>");
    mysqli_close($conn);
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RD Upload</title>
    <link rel="stylesheet" type="text/css" href="rdsty.css">
    <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="dtps.js"></script>
    <script>
        function territorysn() {
            var rg = document.getElementById('regions');
            var ag = document.getElementById('territorys');
            var rvl = rg.options[rg.selectedIndex].text;
            ag.length = 0;
            var httpr = new XMLHttpRequest();
            httpr.onreadystatechange = function () {
                if (httpr.readyState == 4 && httpr.status == 200) {
                    var vl = httpr.responseText;
                    var tmp = vl.split("###");
                    for (var cn = 0; cn < tmp.length; cn++) {
                        var ops = document.createElement("option");
                        ops.text = tmp[cn];
                        ag.add(ops, null);
                    }
                }
            };
            var ops = document.createElement("option");
            ops.text = "All";
            ag.add(ops, null);
            httpr.open("POST", "aj.php?actp=territorysn&sparams=" + rvl, true);
            httpr.send();
        }

        function mnh(mn, bn) {
            document.getElementById("agentsb").style.display = "none";
            document.getElementById("itemsb").style.display = "none";
            document.getElementById("areasb").style.display = "none";
            var cs = document.getElementsByClassName('amn');
            for (var cn = 0; cn < cs.length; cn++) {
                cs[cn].style.background = "white";
            }
            document.getElementById(bn).style.display = "block";
            document.getElementById(mn).style.background = "silver";
        }

        function mch(mn) {
            if (mn.style.background != 'silver') {
                mn.style.background = 'orange';
            }
        }

        function mnc(mn) {
            if (mn.style.background != 'silver') {
                mn.style.background = 'white';
            }
        }
    </script>
</head>
<body style="font-family:calibri; font-size:small" onload="mnh('amnc', 'agentsb')">
<div class="hdn"></div>
<?php
printf("<div class='ses'>%s (%s)</div>", htmlspecialchars($_SESSION['titles']), htmlspecialchars($_SESSION['positions']));
?>
<div class="tops" align="center">Rd upload</div>
<div class="homes"><a href="index.php" style='color:#A9BCF5;'>Sign out</a></div>

<div class="mains">
    <div class="tdt">
        <b>Ensure the CSV file data before uploading as per the required format<br></b>
        The file type should be CSV.<br><br>
        Select the file:

        <form enctype="multipart/form-data" method="POST" action="rdwebupsfa2.php?actp=0">
            <input type="file" id="files" name="files"><br><br>
            <input type="submit" name="file_submit" value="Go"><br>
        </form>
    </div>
</div>
</body>
</html>
