<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);

$m = new Manager();

$output = '';
$datefrom = "";
$dateto = "";
$product_name = "All";

$totalPieces = 0;
$totalCartonDecimal = 0;
$totalSaleAmount = 0;

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

extract($_REQUEST);

// ---- Date handling ----
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}

if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}

$datefrom = date("d-m-Y", strtotime($datefrom));
$dateto   = date("d-m-Y", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo   = date("Y-m-d", strtotime($dateto));

if (!isset($product_name)) {
    $product_name = 'All';
}

/**
 * Build filter for product wise sales report
 */
$filterReport = "
    WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d') >= '$qryDate'
    AND DATE_FORMAT(inv.create_date,'%Y-%m-%d') <= '$qryTo'
    AND inv.status NOT IN('Draft', 'Cancel')
";

if ($product_name != '' && $product_name != 'All') {
    $filterReport .= " AND invPr.product_id = '$product_name' ";
}

$filterReport .= "
    GROUP BY 
        invPr.product_id,
        ps.code,
        ps.name,
        ps.weight,
        ps.unit,
        carton_piece

    ORDER BY 
        ps.name ASC
";

//echo $filterReport;
//echo "<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>

<div id="container">
    <?php include('../includes/inc_top.php'); ?>

    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Product Wise Sales Report</h3>
            </div>

            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });

                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                });
            </script>

            <form action="" method="get" name="search" id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col-lg-4">
                            Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>

                        <td class="col-lg-4">
                            Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>

                    <tr>
                        <td class="col-lg-4">
                            Product<br>
                            <?php
                            $productsFilter = " WHERE deleted = '0' AND status = 'active' ORDER BY name ASC";
                            $products = ProductSetup::GetProductSetupList($productsFilter);
                            ?>

                            <select class="form-control" required id="product_name" name="product_name">
                                <option value="All">All</option>
                                <?php
                                if ($products) {
                                    foreach ($products AS $productRow) {
                                        echo '<option value="' . $productRow->id . '" ';
                                        if ($productRow->id == $product_name) {
                                            echo 'selected';
                                        }
                                        echo '>';

                                        echo $productRow->code . ' - ' . $productRow->name;

                                        if ($productRow->weight != '') {
                                            echo ' ' . $productRow->weight;
                                        }

                                        if ($productRow->unit != '') {
                                            echo ' ' . $productRow->unit;
                                        }

                                        echo '</option>';
                                    }
                                }
                                ?>
                            </select>
                            <br/>
                        </td>

                        <td class="col-lg-4"></td>
                    </tr>

                    <tr>
                        <td colspan="2" class="col-lg-4">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>

                            <?php if (isset($_GET['view'])) { ?>
                                <button type="button"
                                      onclick="exportProductWiseSaleCSV('product-wise-sale-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                      class="btn waves-effect waves-light"
                                      style="float:left; margin-left: 15px;">
                                  Export CSV
                              </button>

                                <button
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>
                        </td>
                    </tr>
                </table>
            </form>

            <hr>

            <?php
            if (isset($_GET['view'])) {

                if ($product_name != '' && $product_name != 'All') {
                    $productObj = ProductSetup::GetProductSetupById($product_name);
                    if (!empty($productObj)) {
                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                        echo "<h4 style='text-align: center;'>" . $productObj->name . " - Product</h4>";
                        echo '</th></tr></table>';
                    }
                }
                ?>

                <div id="floatThead" class="adv-table section">
                    <table class="striped demo1 bordered" id="reportTable">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            
                            <th>Product Name</th>
                            <th>Weight</th>
                            <th>Unit</th>
                            <th style="text-align: right;">Pieces / Carton</th>
                            <th style="text-align: right;">Total Pieces Sold</th>
                            
                            <th style="text-align: right;">Carton</th>
                            <th style="text-align: right;">Gross Sale Amount</th>
                        </tr>
                        </thead>

                        <tbody>
                        <?php
                        $qry = Invoice::GetProductWiseSalesReport($filterReport);
                        $counter = 0;

                        if ($qry) {
                            foreach ($qry as $qery) {
                                $counter++;

                                $cartonDisplay = number_format($qery->full_cartons, 0) . ' Ctn';

                                if ($qery->loose_pieces > 0) {
                                    $cartonDisplay .= ' + ' . number_format($qery->loose_pieces, 0) . ' Pcs';
                                }

                                $totalPieces += $qery->total_pieces;
                                $totalCartonDecimal += $qery->carton_decimal;
                                $totalSaleAmount += $qery->gross_sale_amount;
                                ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter ?></td>
                                    
                                    <td><?= $qery->product_name ?></td>
                                    <td><?= $qery->product_weight ?></td>
                                    <td><?= $qery->product_unit ?></td>
                                    <td style="text-align: right;">
                                        <?= number_format($qery->carton_piece, 0) ?>
                                    </td>
                                    <td style="text-align: right;">
                                        <?= number_format($qery->total_pieces, 0) ?>
                                    </td>
                                    
                                    <td style="text-align: right;">
                                        <?= number_format($qery->carton_decimal, 2, '.', '') ?>
                                    </td>
                                    <td style="text-align: right;">
                                        <?= number_format($qery->gross_sale_amount, 2, '.', '') ?>
                                    </td>
                                </tr>
                                <?php
                            }
                        } else {
                            ?>
                            <tr>
                                <td colspan="10" style="text-align: center; border: 1px solid #666;">
                                    No record found.
                                </td>
                            </tr>
                            <?php
                        }
                        ?>

                        <tr>
                          	<th></th>
                          <th></th>
                          <th></th>
                          <th></th>
                            <th  style="text-align: right; border: 1px solid #000;">
                                Total
                            </th>

                            <th style="text-align: right; border: 1px solid #000;">
                                <?= number_format($totalPieces, 0) ?>
                            </th>

                           

                            <th style="text-align: right; border: 1px solid #000;">
                                <?= number_format($totalCartonDecimal, 2, '.', '') ?>
                            </th>

                            <th style="text-align: right; border: 1px solid #000;">
                                <?= number_format($totalSaleAmount, 2, '.', '') ?>
                            </th>
                        </tr>

                        </tbody>
                    </table>
                </div>

                <?php
            }
            ?>
        </div>
    </div>
</div>

<?php include('../includes/inc_footer.php'); ?>

<script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
<?php include('../includes/inc_js.php'); ?>

<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead.min.js"></script>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead-slim.min.js"></script>

<script type="text/javascript">
function exportProductWiseSaleCSV(filename) {
    var csv = [];

    // Report title
    csv.push('"Product Wise Sales Report"');

    // Period
    csv.push('"Period: <?= $datefrom ?> To <?= $dateto ?>"');

    <?php
    if ($product_name != '' && $product_name != 'All') {
        $productObj = ProductSetup::GetProductSetupById($product_name);
        if (!empty($productObj)) {
            ?>
            csv.push('"Product: <?= addslashes($productObj->name) ?>"');
            <?php
        }
    }
    ?>

    // Empty line
    csv.push('');

    // Table headers according to your final report
    csv.push([
        '"S.No"',
        '"Product Name"',
        '"Weight"',
        '"Unit"',
        '"Pieces / Carton"',
        '"Total Pieces Sold"',
        '"Carton"',
        '"Gross Sale Amount"'
    ].join(','));

    // Table rows
    var rows = document.querySelectorAll("#reportTable tbody tr");

    for (var i = 0; i < rows.length; i++) {
        var cols = rows[i].querySelectorAll("td, th");

        // Skip "No record found" row if present
        if (cols.length === 1) {
            continue;
        }

        // Your final report has 8 columns
        if (cols.length < 8) {
            continue;
        }

        var row = [];

        for (var j = 0; j < 8; j++) {
            var data = cols[j].innerText || cols[j].textContent || '';

            data = data.replace(/(\r\n|\n|\r)/gm, " ");
            data = data.replace(/\s+/g, " ");
            data = data.trim();
            data = data.replace(/"/g, '""');

            row.push('"' + data + '"');
        }

        csv.push(row.join(","));
    }

    var csvFile = new Blob([csv.join("\n")], { type: "text/csv;charset=utf-8;" });
    var downloadLink = document.createElement("a");

    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}
</script>

</body>
</html>