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

$m = new Manager();

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

$output = '';
$datefrom = "";
$dateto = "";
$cat_name = "All";
$customer_name = "All";

extract($_REQUEST);

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

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

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

// ---------- Build filter ----------
$filterReport  = " WHERE DATE(inv.create_date) >= '" . $datefrom . "'
                   AND DATE(inv.create_date) <= '" . $dateto . "'
                   AND inv.status NOT IN ('Draft', 'Cancel') ";

// Category filter
if (isset($cat_name) && $cat_name != '' && $cat_name != 'All') {
    $filterReport .= " AND cs.category_id = '" . intval($cat_name) . "' ";
}

// Optional customer filter (future use)
// if (isset($customer_name) && $customer_name != '' && $customer_name != 'All') {
//     $filterReport .= " AND inv.customer_id = '" . intval($customer_name) . "' ";
// }

$filterReport .= " ORDER BY inv.create_date ASC, cc.name ASC, cs.name ASC, inv.id ASC, invPr.id ASC ";
?>
<!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">

            <h3>Detailed Sales Report (Invoice & Products)</h3>

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

            <!-- FILTER FORM -->
            <form action="" method="get" name="search" id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col s4">
                            Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $displayFrom; ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" value="1" class="form-control"/>
                        </td>
                        <td class="col s4">
                            Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $displayTo; ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col s4">
                            Category<br>
                            <?php
                            $catFilter = " JOIN customer_setup ON customer_category.id = customer_setup.category_id
                                           GROUP BY customer_category.id
                                           ORDER BY customer_category.name ASC";
                            $categories = CustomerCategorySetup::GetCustomerCategorySetupList($catFilter);
                            ?>
                            <select class="form-control" id="cat_name" name="cat_name">
                                <option value="All">All</option>
                                <?php
                                if ($categories) {
                                    foreach ($categories as $rowCat) {
                                        ?>
                                        <option value="<?= $rowCat->catid; ?>" <?= ($rowCat->catid == $cat_name ? 'selected' : ''); ?>>
                                            <?= $rowCat->catname; ?>
                                        </option>
                                        <?php
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3" class="col s12">
                            <button type="submit" class="btn waves-effect waves-light" style="float:left;">
                                Search
                            </button>

                            <?php if (isset($_GET['view'])) { ?>
                                <button type="button"
                                        id="exportcsv"
                                        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'])) {

                $rows = Invoice::GetInvoiceSalesDetailReport($filterReport);

                $invoices = array();

                if ($rows) {
                    foreach ($rows as $r) {

                        $invId = $r->invoice_id;

                        if (!isset($invoices[$invId])) {
                            $invoices[$invId] = array(
                                'invoice_id'               => $r->invoice_id,
                                'invoice_code'             => $r->invoice_code,
        						'po_number'                => $r->po_number,
                                'create_date'              => $r->create_date,
                                'customer_id'              => $r->customer_id,
                                'customer_name'            => $r->customer_name,
                                'customer_category_id'     => $r->customer_category_id,
                                'customer_category_name'   => !empty($r->customer_category_name) ? $r->customer_category_name : 'N/A',
                                'customer_adv_tax_enabled' => $r->customer_adv_tax_enabled,
                                'customer_adv_tax_perc'    => $r->customer_adv_tax_perc,
                                'invoice_discount_amount'  => floatval($r->invoice_discount_amount),
                                'invoice_is_tax'           => $r->invoice_is_tax,
                                'invoice_tax'              => floatval($r->invoice_tax),
                                'invoice_tax_amount'       => floatval($r->invoice_tax_amount),
                                'invoice_adv_tax_rate'     => floatval($r->invoice_adv_tax_rate),
                                'invoice_adv_tax_amount'   => floatval($r->invoice_adv_tax_amount),
                                'invoice_total_amount'     => floatval($r->invoice_total_amount),
                                'invoice_payment_due'      => floatval($r->invoice_payment_due),
                                'lines'                    => array(),
                                'invoice_gross_total'      => 0
                            );
                        }

                        $carton = 0;
                        if (!empty($r->carton_piece) && floatval($r->carton_piece) > 0) {
                            $carton = floatval($r->product_qty) / floatval($r->carton_piece);
                        }

                        $qtyPcs = floatval($r->product_qty);

                        $weightPerPieceKg = 0;
                        $unitLower = strtolower(trim($r->product_unit));

                        if ($unitLower == 'gm' || $unitLower == 'g') {
                            $weightPerPieceKg = floatval($r->product_weight) / 1000;
                        } elseif ($unitLower == 'kg') {
                            $weightPerPieceKg = floatval($r->product_weight);
                        } elseif ($unitLower == 'mg') {
                            $weightPerPieceKg = floatval($r->product_weight) / 1000000;
                        } else {
                            $weightPerPieceKg = 0;
                        }

                        $lineWeightKg = $weightPerPieceKg * $qtyPcs;
                        $lineGross    = $qtyPcs * floatval($r->unit_sale_price);

                        $line = array(
                            'invoice_product_id' => $r->invoice_product_id,
                            'product_id'         => $r->product_id,
                            'product_name'       => $r->product_name,
                            'product_weight'     => $r->product_weight,
                            'product_unit'       => $r->product_unit,
                            'carton'             => $carton,
                            'qty_pcs'            => $qtyPcs,
                            'line_weight_kg'     => $lineWeightKg,
                            'unit_sale_price'    => floatval($r->unit_sale_price),
                            'line_gross'         => $lineGross
                        );

                        $invoices[$invId]['lines'][] = $line;
                        $invoices[$invId]['invoice_gross_total'] += $lineGross;
                    }
                }

                $grand_carton    = 0;
                $grand_qty       = 0;
                $grand_weight_kg = 0;
                $grand_gross     = 0;
                $grand_discount  = 0;
                $grand_excl      = 0;
                $grand_tax       = 0;
                $grand_adv_tax   = 0;
                $grand_incl      = 0;
                ?>

                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th colspan="13" style="text-align:center;">
                                Period: <?= $displayFrom; ?> to <?= $displayTo; ?>
                                <?php
                                if ($cat_name != 'All') {
                                    $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
                                    if ($catObj) {
                                        echo " | Category: " . $catObj->name;
                                    }
                                }
                                ?>
                            </th>
                        </tr>
                        <tr style="border: 1px solid #666; background:#ECEFF1;">
                            <th>S.No</th>
                            <th>Invoice # / Date / Customer</th>
                            <th>Product</th>
                            <th>Weight</th>
                            <th>Carton</th>
                            <th>Quantity</th>
                            <th>Total Weight (KG)</th>
                            <th>Gross Value</th>
                            <th>Disc. Value</th>
                            <th>Value Excl. Sales Tax</th>
                            <th>Sales Tax Value</th>
                            <th>Adv. Tax Value</th>
                            <th>Value Incl. Sales Tax + Adv. Tax</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $srno = 1;

                        if (!empty($invoices)) {
                            foreach ($invoices as $inv) {

                                $invoiceTaxRate    = ($inv['invoice_is_tax'] == 1) ? floatval($inv['invoice_tax']) : 0;
                                $invoiceDiscount   = floatval($inv['invoice_discount_amount']);
                                $invoiceGrossTotal = floatval($inv['invoice_gross_total']);

                                $invoiceAdvTaxAmount = 0;
                                if (!empty($inv['customer_adv_tax_enabled']) && $inv['customer_adv_tax_enabled'] == 1) {
                                    $invoiceAdvTaxAmount = floatval($inv['invoice_adv_tax_amount']);
                                }

                                $inv_carton    = 0;
                                $inv_qty       = 0;
                                $inv_weight_kg = 0;
                                $inv_gross     = 0;
                                $inv_discount  = 0;
                                $inv_excl      = 0;
                                $inv_tax       = 0;
                                $inv_adv_tax   = 0;
                                $inv_incl      = 0;
                                ?>
                                <tr style="border:1px solid #666; background:#f5f5f5;">
                                    <td><?= $srno++; ?></td>
                                    <td colspan="12">
                                        <strong>Invoice:</strong> <?= $inv['invoice_code']; ?>
                                        &nbsp; | &nbsp;
                                        <strong>PO #:</strong> <?= (!empty($inv['po_number']) ? $inv['po_number'] : 'N/A'); ?>
                                        &nbsp; | &nbsp;
                                        <strong>Date:</strong> <?= date('d-m-Y h:i A', strtotime($inv['create_date'])); ?>
                                        &nbsp; | &nbsp;
                                        <strong>Customer:</strong> <?= $inv['customer_name']; ?>
                                        &nbsp; | &nbsp;
                                        <strong>Tax Rate:</strong> <?= number_format($invoiceTaxRate, 2); ?>%
                                        <?php if ($invoiceAdvTaxAmount > 0) { ?>
                                            &nbsp; | &nbsp;
                                            <strong>Adv. Tax:</strong> <?= number_format($invoiceAdvTaxAmount, 2); ?>
                                        <?php } ?>
                                    </td>
                                </tr>
                                <?php

                                foreach ($inv['lines'] as $line) {

                                    $share = ($invoiceGrossTotal > 0) ? ($line['line_gross'] / $invoiceGrossTotal) : 0;
                                    $line_discount = $share * $invoiceDiscount;
                                    $value_excl    = $line['line_gross'] - $line_discount;
                                    $line_tax      = $value_excl * ($invoiceTaxRate / 100);

                                    // distribute invoice advance tax proportionally to each product line
                                    $line_adv_tax = $share * $invoiceAdvTaxAmount;

                                    $value_incl = $value_excl + $line_tax + $line_adv_tax;

                                    $inv_carton    += $line['carton'];
                                    $inv_qty       += $line['qty_pcs'];
                                    $inv_weight_kg += $line['line_weight_kg'];
                                    $inv_gross     += $line['line_gross'];
                                    $inv_discount  += $line_discount;
                                    $inv_excl      += $value_excl;
                                    $inv_tax       += $line_tax;
                                    $inv_adv_tax   += $line_adv_tax;
                                    $inv_incl      += $value_incl;
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td></td>
                                        <td></td>
                                        <td><?= $line['product_name']; ?></td>
                                        <td style="text-align:right;"><?= $line['product_weight'] . ' ' . $line['product_unit']; ?></td>
                                        <td style="text-align:right;"><?= number_format($line['carton'], 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($line['qty_pcs'], 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($line['line_weight_kg'], 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($line['line_gross'], 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($line_discount, 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($value_excl, 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($line_tax, 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($line_adv_tax, 2); ?></td>
                                        <td style="text-align:right;"><?= number_format($value_incl, 2); ?></td>
                                    </tr>
                                    <?php
                                }

                                ?>
                                <tr style="border:1px solid #000; font-weight:bold; background:#e0e0e0;">
                                    <td></td>
                                    <td>Invoice Total:</td>
                                    <td></td>
                                    <td></td>
                                    <td style="text-align:right;"><?= number_format($inv_carton, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_qty, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_weight_kg, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_gross, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_discount, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_excl, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_tax, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_adv_tax, 2); ?></td>
                                    <td style="text-align:right;"><?= number_format($inv_incl, 2); ?></td>
                                </tr>
                                <?php

                                $grand_carton    += $inv_carton;
                                $grand_qty       += $inv_qty;
                                $grand_weight_kg += $inv_weight_kg;
                                $grand_gross     += $inv_gross;
                                $grand_discount  += $inv_discount;
                                $grand_excl      += $inv_excl;
                                $grand_tax       += $inv_tax;
                                $grand_adv_tax   += $inv_adv_tax;
                                $grand_incl      += $inv_incl;
                            }

                            ?>
                            <tr style="border:2px solid #000; font-weight:bold; background:#cfd8dc;">
                                <td></td>
                                <td>GRAND TOTAL:</td>
                                <td></td>
                                <td></td>
                                <td style="text-align:right;"><?= number_format($grand_carton, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_qty, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_weight_kg, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_gross, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_discount, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_excl, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_tax, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_adv_tax, 2); ?></td>
                                <td style="text-align:right;"><?= number_format($grand_incl, 2); ?></td>
                            </tr>
                            <?php
                        } else {
                            ?>
                            <tr>
                                <td colspan="13" style="text-align:center;">No records found for selected criteria.</td>
                            </tr>
                            <?php
                        }
                        ?>
                        </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="application/javascript">
    $(document).ready(function () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/sales_detailed.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });

        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });

        $('table.demo1 thead').css('background', '#ECEFF1');
    });
  
  $("#exportcsv").on("click", function (e) {
    e.preventDefault();
    $('#searchfrm').prop('target', '_blank');
    $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/sales_detailed_csv.php?").submit();

    setTimeout(function () {
        $('#searchfrm').prop('target', "");
        $('#searchfrm').prop('action', "");
    }, 1000);
});
  
</script>
</body>
</html>