<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
session_start();
if (!isset($_SESSION['userrole'])) {
    header("location: index.php");
    exit;
}
require_once 'functions.php';

$db = login();

//$dbsm = loginsms();

if(isset($_GET['sstooop']))
{
    $status=$_GET['sstooop'];
}
else
{
    $status='';
}

?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--favicon-->
    <link rel="icon" href="assets/images/logo.png" type="image/png" />
    <!--plugins-->
    <link href="assets/plugins/vectormap/jquery-jvectormap-2.0.2.css" rel="stylesheet" />
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="assets/plugins/datatable/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <!-- loader-->
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;display=swap" rel="stylesheet">
    <link href="assets/css/app.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <!-- Theme Style CSS -->
    <link rel="stylesheet" href="assets/css/dark-theme.css" />
    <link rel="stylesheet" href="assets/css/semi-dark.css" />
    <link rel="stylesheet" href="assets/css/header-colors.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@animxyz/core">
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Fetch product amount on product selection change
        document.getElementById('region').addEventListener('change', function() {
            var productId = this.value;
            if (productId) {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'fetch_product_amount.php', true);
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.querySelector('input[name="product_amount"]').value = xhr
                            .responseText;
                        calculateTotal();
                    }
                };
                xhr.send('product_id=' + productId);
            } else {
                document.querySelector('input[name="product_amount"]').value = '';
                calculateTotal();
            }
        });

        // Calculate total amount on quantity keyup
        document.querySelector('input[name="quantity"]').addEventListener('keyup', function() {
            calculateTotal();
        });

        function calculateTotal() {
            var amount = parseFloat(document.querySelector('input[name="product_amount"]').value) || 0;
            var quantity = parseInt(document.querySelector('input[name="quantity"]').value) || 0;
            var totalAmount = amount * quantity;

            let formattedNumber = totalAmount.toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
            //console.log(formattedNumber);

            document.getElementById('totalamount').value = formattedNumber;
        }
    });
    </script>


    <title>OPTIMAL (T) LTD</title>
</head>

<body style="background-color: #e1e0e7;" onload="getLocation()">
    <!--wrapper-->
    <div class="wrapper">
        <!--sidebar wrapper -->
        <?php include_once 'adminmenusales.php' ?>
        <!--end sidebar wrapper -->
        <!--start header -->
        <?php include_once 'header.php' ?>
        <!--end header -->
        <!--start page wrapper -->
        <div class="page-wrapper">
            <div class="page-content">
                <div class="page-title-box">
                    <div class="container">
                        <div class="row align-items-center">
                            <div class="col-lg-8 col-md-7 col-sm-12">
                                <h6 class="page-title">Dashboard</h6>
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item active">Welcome to Administrator Dashboard</li>
                                </ol>
                            </div>
                            <div class="col-lg-4 col-md-5 col-sm-12 text-md-end text-center mt-2 mt-md-0">
                                <button class="btn btn-primary btn-sm" type="button" id="dropdownMenuButton"
                                    aria-expanded="false" onclick="myFunction()">
                                    Add New Order
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <br />
                <!--<div class="row row-cols-1 row-cols-md-2 row-cols-xl-3">
                    <div class="col">
                        <div class="card radius-10 bg-primary bg-gradient">
                            <div class="card-body" style="background-color: #00478a;border-radius:5px;color:#ffffff;">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <p class="mb-0 text-white">Registered Customers</p>
                                        <h4 class="my-1 text-white">7</h4>
                                    </div>
                                    <div class="text-white ms-auto font-35"><i class="bx bx-user-plus"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card radius-10 bg-success bg-gradient">
                            <div class="card-body" style="background-color: #00478a;border-radius:5px;color:#ffffff;">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <p class="mb-0 text-white">Distributed Orders</p>
                                        <h4 class="my-1 text-white">23</h4>
                                    </div>
                                    <div class="text-white ms-auto font-35"><i class="bx bx-file"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card radius-10 bg-warning bg-gradient">
                            <div class="card-body" style="background-color: #00478a;border-radius:5px;color:#ffffff;">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <p class="mb-0 text-white">Products Registered</p>
                                        <h4 class="my-1 text-white">39</h4>
                                    </div>
                                    <div class="text-white ms-auto font-35"><i class="bx bx-current-location"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card radius-10 bg-danger bg-gradient" style="background-color: #00478a;border-radius:5px;">
                            <div class="card-body" style="background-color: #00478a;border-radius:5px;color:#ffffff;">
                                <div class="d-flex align-items-center" style="color:#ffffff;">
                                    <div>
                                        <p class="mb-0 text-white" style="color:#ffffff;">Orders Pending Collections</p>
                                        <h4 class="text-white my-1" style="color:#ffffff;">5</h4>
                                    </div>
                                    <div class="text-white ms-auto font-35"><i class="bx bx-webcam"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>-->
                <br />
                <div id="myDIV" style="display:none;">
                    <div class="row">
                        <div class="col-sm-12">
                            <br>
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="card-title">Order Distribution Form</h4>
                                    <!--<p class="card-title-desc">Kindly Fill the below Details</p>-->
                                    <form class="row g-3" action="insertscript" method="POST">

                                        <div class="col-md-12">
                                            <label for="input1" class="form-label">Customer Name:</label>
                                            <select class="form-control show-tick" name="customer_dinsert"
                                                id="customer_dinsert" required
                                                style="width: 100%;box-sizing: border-box;border: 2px solid #ccc;">
                                                <option value="" disabled selected>--Please select Customer
                                                    Name--
                                                </option>
                                                <?php 
                                                                $sql_gete = "SELECT * FROM  tbl_crips_customer order by customer_name asc";
                                                                $result_set = mysqli_query($db, $sql_gete);
                                                                while ($row = mysqli_fetch_array($result_set, MYSQLI_ASSOC)) {
                                                            ?>
                                                <option value="<?php echo $row['id'];?>">
                                                    <?php echo $row['customer_name'];?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        <br />

                                        <div id="productContainer">
                                            <div class="product-group row g-3 mb-3">
                                                <div class="col-md-6">
                                                    <label for="region" class="form-label">Product Name</label>
                                                    <select class="form-control" name="region[]" required>
                                                        <option value="" disabled selected>--Please select Product--
                                                        </option>
                                                        <?php 
                                                            $sql_gete = "SELECT * FROM tbl_crips_product ORDER BY product_name ASC";
                                                            $result_set = mysqli_query($db, $sql_gete);
                                                            while ($row = mysqli_fetch_array($result_set, MYSQLI_ASSOC)) {
                                                        ?>
                                                        <option value="<?php echo $row['id'];?>">
                                                            <?php echo $row['product_name'];?>
                                                        </option>
                                                        <?php } ?>
                                                    </select>
                                                </div>

                                                <div class="col-md-6">
                                                    <label for="product_amount" class="form-label">Amount:</label>
                                                    <input type="text" name="product_amount[]" class="form-control"
                                                        readonly>
                                                </div>

                                                <div class="col-md-6">
                                                    <label for="quantity" class="form-label">Quantity:</label>
                                                    <input type="text" name="quantity[]" class="form-control" required>
                                                </div>

                                                <div class="col-md-6">
                                                    <label for="totalamount" class="form-label">Total Amount:</label>
                                                    <input type="text" name="totalamount[]" class="form-control"
                                                        readonly>
                                                </div>

                                                <div class="col-12 text-end">
                                                    <button type="button" class="btn btn-danger btn-sm"
                                                        onclick="removeProduct(this)">Remove</button>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-12 text-center">
                                            <button type="button" class="btn btn-secondary" onclick="addProduct()">Add
                                                Product</button>
                                            <button type="submit" class="btn btn-primary"
                                                style="width: 300px;">Save</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!--end row-->


                <br />
                <div class="card">
                    <div class="card-body">
                        <p class="mb-0 text-uppercase">Distribution History</p>
                        <br />
                        <div class="table-responsive">
                            <div class="text-center">
                                <?php if (!empty($status)) : ?>
                                <div class="alert alert-success">

                                    <?php echo $status ?>

                                </div>
                                <?php endif ?>
                            </div>
                            <table id="example" class="table table-striped table-bordered" style="width:100%">
                                <thead>
                                    <tr>
                                        <th class="text-center">S/N</th>
                                        <th class="text-center">Product Name</th>
                                        <th class="text-center">Date</th>
                                        <th class="text-center">Amount(Tsh)</th>
                                        <th class="text-center">Quantity</th>
                                        <th class="text-center">Total Amount(Tsh)</th>
                                        <th class="text-center">Payment Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $x = 1;
                                    $sales_id=$_SESSION['user_id'];
                                    $sql_gete = "SELECT * FROM   tbl_crips_order where sales_id='$sales_id' order by reg_date desc";
                                    $result_set = mysqli_query($db, $sql_gete);
                                    while ($row = mysqli_fetch_array($result_set, MYSQLI_ASSOC)) {

                                    ?>
                                    <tr>
                                        <td align="center" style="width: 20px;"><?php echo $x; ?></td>
                                        <td align="center" style="width: 50px;">
                                            <?php echo get_product_name($db,$row['product_id']); ?></td>
                                        <td align="center" style="width: 50px;"><?php echo $row['reg_date']; ?></td>
                                        <td align="center" style="width: 50px;">
                                            <?php echo number_format($row['amount'],2); ?></td>
                                        <td align="center" style="width: 50px;"><?php echo $row['quantity']; ?></td>
                                        <td align="center" style="width: 50px;">
                                            <?php echo number_format($row['total_amount'],2); ?></td>
                                        <td align="center" style="width: 50px;"><?php echo $row['payment_status']; ?>
                                        </td>
                                    </tr>
                                    <?php 
                                        $x++;
                                    } 
                                    ?>
                                </tbody>
                            </table>
                            </table>
                        </div>
                    </div>
                </div>
                <br />
                <br />
                <!--End Row-->

            </div>
        </div>
        <br />
        <br />
        <!--end page wrapper -->
        <!--start overlay-->
        <div class="overlay toggle-icon"></div>
        <!--end overlay-->
        <!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i
                class='bx bxs-up-arrow-alt'></i></a>
        <!--End Back To Top Button-->
        <footer class="page-footer" style="background-color:#fff;color:#000;">
            <p class="mb-0">Copyright © <?php echo date('Y'); ?>. All right reserved.</p>
        </footer>
    </div>
    <!--end wrapper-->
    <!--start switcher-->

    <!--end switcher-->
    <!-- Bootstrap JS -->
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <!--plugins-->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
    <script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
    <script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
    <script src="assets/plugins/chartjs/js/Chart.min.js"></script>
    <script src="assets/plugins/vectormap/jquery-jvectormap-2.0.2.min.js"></script>
    <script src="assets/plugins/vectormap/jquery-jvectormap-world-mill-en.js"></script>
    <script src="assets/plugins/jquery.easy-pie-chart/jquery.easypiechart.min.js"></script>
    <script src="assets/plugins/sparkline-charts/jquery.sparkline.min.js"></script>
    <script src="assets/plugins/jquery-knob/excanvas.js"></script>
    <script src="assets/plugins/jquery-knob/jquery.knob.js"></script>
    <script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
    <script src="assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
    <script src="//cdn.ckeditor.com/4.19.1/standard/ckeditor.js"></script>
    <script>
        function addProduct() {
            var productGroup = document.querySelector('.product-group').cloneNode(true);
            document.getElementById('productContainer').appendChild(productGroup);
        }

        function removeProduct(button) {
            var productGroup = button.closest('.product-group');
            productGroup.remove();
        }
    </script>
    <script>
    function myMap() {
        var mapOptions = {
            center: new google.maps.LatLng(-6.77864738337831, 39.25218466870695),
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.HYBRID
        }
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);
        var goldenGatePosition = {
            lat: -6.7786473,
            lng: 39.2521846
        };
        var marker = new google.maps.Marker({
            position: goldenGatePosition,
            map: map,
            title: 'TP'
        });
    }

    $('.counter-count').each(function() {
        $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
        }, {
            duration: 5000,
            easing: 'swing',
            step: function(now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCTCp2CP3cO1q6vY7MR_I6mBjMgY-OvmUg&callback=myMap">
    </script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('region').addEventListener('change', function() {
            var regionID = this.value;
            if (regionID) {
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'fetch_districts.php', true);
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.getElementById('district').innerHTML = xhr.responseText;
                    }
                };
                xhr.send('region_id=' + regionID);
            } else {
                document.getElementById('district').innerHTML =
                    '<option value="">--Please select --</option>';
            }
        });
    });
    </script>
    <script>
    CKEDITOR.replace('docinstruction');
    </script>
    <script>
    var pp = 535;
    console.log(pp);
    let pieOptions = {
        series: [65, 6, 3, 2],
        chart: {
            type: 'pie',
            height: 350,
            toolbar: {
                show: true,
                tools: {
                    download: true // <== line to add
                }
            }
        },
        labels: ['Answered', 'No Answer', 'Failed', 'Cancelled'],
        theme: {
            monochrome: {
                enabled: false
            }
        },
        title: {
            text: 'Percantage Per Call Status'
        },
        colors: ["#07da63", "#D2042D", "#FFC300", "#000000"],
        responsive: [{
            breakpoint: 380,
            options: {
                chart: {
                    width: 200
                },
                legend: {
                    position: 'bottom'
                }
            }
        }]
    };
    let pieChart = new ApexCharts(document.querySelector("#pie-chart"), pieOptions);
    pieChart.render();
    </script>
    <script>
    let memberContributionOptions = {
        series: [{
            name: "Registered Calls Per Region",
            data: [{
                    x: 'Dar es Salaam',
                    y: 34
                },
                {
                    x: 'Mbeya',
                    y: 52
                },
                {
                    x: 'Kigoma',
                    y: 20
                },
                {
                    x: 'Tabora',
                    y: 24
                },
                {
                    x: 'Kwengineko',
                    y: 19
                }
            ]
        }],
        colors: ['#00478a'],
        chart: {
            type: 'bar',
            height: 350
        },
        xaxis: {
            type: 'category',
            labels: {

            }
        },
        title: {
            text: 'Registered Calls Per Region',
        },
    };
    let memberChart = new ApexCharts(document.querySelector("#member-contribution-chart"), memberContributionOptions);
    memberChart.render();
    </script>
    <script>
    $(document).ready(function() {
        $('#example').DataTable();
    });
    </script>

    <script>
    $(document).ready(function() {
        var table = $('#example2').DataTable({
            lengthChange: false,
            buttons: ['copy', 'excel', 'pdf', 'print']
        });

        table.buttons().container()
            .appendTo('#example2_wrapper .col-md-6:eq(0)');
    });
    </script>
    <script>
    $(document).ready(function() {
        var table = $('#example2').DataTable({
            lengthChange: false,
            buttons: ['excel']
        });

        table.buttons().container()
            .appendTo('#example2_wrapper .col-md-6:eq(0)');
    });
    </script>
    <script type="text/javascript">
    function myFunction() {
        var x = document.getElementById("myDIV");
        var y = document.getElementById("myDIV2");
        var z = document.getElementById("myDIV3");
        if (x.style.display === "none") {
            x.style.display = "block";
            y.style.display = "none";
            z.style.display = "none";
        } else {
            x.style.display = "none";
            y.style.display = "none";
            z.style.display = "none";
        }
    }
    </script>

    <script type="text/javascript">
    function myFunction2() {
        var x = document.getElementById("myDIV2");
        var y = document.getElementById("myDIV");
        var z = document.getElementById("myDIV3");
        if (x.style.display === "none") {
            x.style.display = "block";
            y.style.display = "none";
            z.style.display = "none";
        } else {
            x.style.display = "none";
            y.style.display = "none";
            z.style.display = "none";
        }
    }
    </script>
    <script type="text/javascript">
    function myFunction3() {
        var x = document.getElementById("myDIV3");
        var y = document.getElementById("myDIV");
        var z = document.getElementById("myDIV2");
        if (x.style.display === "none") {
            x.style.display = "block";
            y.style.display = "none";
            z.style.display = "none";
        } else {
            x.style.display = "none";
            y.style.display = "none";
            z.style.display = "none";
        }
    }
    </script>
    <script>
    $(function() {
        $(".knob").knob();
    });
    </script>
    <script src="assets/js/index.js"></script>
    <!--app JS-->
    <script src="assets/js/app.js"></script>


</body>

</html>