<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = '';
$dateto = '';
$customer_id= '';
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
if (isset($_POST) && !empty($_GET['validate'])) {
    $data['status'] = 'Pending';
    $data['validate_date'] = 'Now()';
    Invoice::UpdateInvoiceSetup($_GET['validate'], $data);
    header("Location: " . PROJECT_ADMIN_URL . "transaction/invoice.php?view");
    exit();
}
if (isset($_POST) && !empty($_GET['cancel'])) {
    global $db;

    $invoiceId = (int)$_GET['cancel'];

    // 1) RESTORE STOCK FROM INVOICE_STOCK_USAGE (same logic as edit)
    $usages = $db->fetch_all_array("
        SELECT * 
        FROM " . TABLE_INVOICE_STOCK_USAGE . " 
        WHERE invoice_id = '{$invoiceId}'
    ");

    if ($usages && $db->affected_rows > 0) {
        foreach ($usages as $u) {
            $qtyUsed = (int)$u->qty_used;
            $stockId = (int)$u->stock_id;

            // add back to stock and reverse deducted_qty
            $db->query("
                UPDATE " . TABLE_STOCK . "
                SET 
                    deducted_qty  = deducted_qty - {$qtyUsed},
                    remaining_qty = remaining_qty + {$qtyUsed}
                WHERE id = {$stockId}
            ");
        }

        // remove usage records for this invoice
        $db->query("
            DELETE FROM " . TABLE_INVOICE_STOCK_USAGE . "
            WHERE invoice_id = '{$invoiceId}'
        ");
    }

    // 2) UPDATE INVOICE STATUS TO Cancel
    $data = [];
    $data['status']        = 'Cancel';
    $data['validate_date'] = 'Now()';
    Invoice::UpdateInvoiceSetup($invoiceId, $data);

    header("Location: " . PROJECT_ADMIN_URL . "transaction/invoice.php?view");
    exit();
}

if (isset($_POST) && !empty($_GET['paid'])) {
    $data['status'] = 'Paid';
    $data['validate_date'] = 'Now()';
    Invoice::UpdateInvoiceSetup($_GET['paid'], $data);
    header("Location: " . PROJECT_ADMIN_URL . "transaction/invoice.php?view");
    exit();
}
extract($_REQUEST);
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-90 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));
$filter = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel' ";
$filter .= " ORDER BY name";
$customer_id = $_GET['customer_id'] ?? 'All'; // Use GET instead of POST
$filter = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel' ";
if (!empty($customer_id) && $customer_id !== "All") {
    $customer_id = intval($customer_id); // Sanitize input
    $filter .= " AND customer_id = $customer_id"; // Add supplier filter
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <style>
        .fa-credit-card:before, .fa-edit:before, .fa-pencil-square-o:before, .fa-check-circle:before, .fa-check-square-o:before, .fa-arrows-alt:before {
            margin-right: 3px;
        }
        table{
            font-size: 18px;
        }
    </style>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Invoices</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 l4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="datepicker form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col l4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="datepicker form-control"/>
                        </td>
                        <td class="col s4">Customer<br>
                            <?php
                            $filterCustomer = " WHERE status = 'active'";
                            $customers = CustomerSetup::GetCustomerSetupList($filterCustomer);
                            ?>
                            <select class="form-control" required id="customer_id"
                                    name="customer_id">
                                <option>All</option>
                                <?php
                                if ($customers) {
                                    foreach ($customers as $customer) {
                                        echo '<option ';
                                        if ($customer->id == $customer_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $customer->id . '" >' . $customer->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                        <td class="col l4">&nbsp;<br>
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                        </td>
                    </tr>
                </table>
            </form>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;"
                       href="invoice_create.php?add">Add <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
            if (isset($_GET['view'])) {

                ?>
                <?php if (isset($_GET['sucess'])) { ?>
                    <div id='card-alert' class='card green lighten-5'>
                        <div class='card-content green-text'>
                            <p>Successfully updated!</p>
                        </div>
                        <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <?php if (isset($_GET['error'])) { ?>
                    <div id='card-alert' class='card orange lighten-5'>
                        <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>Error occurred!</p>
                        </div>
                        <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <div class="table-datatables">
                    <table id="data-table-simple" class=" striped responsive-table">
                        <thead>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Code</th>
                            <th>Customer</th>
                            <th>Sales Person</th>
                            <th>Status</th>
                            <th>Invoice Amount</th>
                            <th>Payment Received</th>
                            <th>Balance Amount</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Code</th>
                            <th>Customer</th>
                            <th>Sales Person</th>
                            <th>Status</th>
                            <th>Invoice Amount</th>
                            <th>Payment Received</th>
                            <th>Balance Amount</th>
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = Invoice::GetInvoiceList($filter);
                        if ($qry) {
                            foreach ($qry as $qery) {
                                // Initialize total payment received for the current invoice
                                $totalPaymentReceived = 0;

                                // Fetch payment data for the current invoice
                                $filterPayment = "WHERE invoice_reference_code = '{$qery->id}' AND status <> 'Cancel'";
                                $paymentData = Payment::GetPaymentList($filterPayment);

                                if ($paymentData) {
                                    foreach ($paymentData as $payment) {
                                        $totalPaymentReceived += $payment->amount;
                                    }
                                }

                                // Calculate the balance amount
                                $balanceAmount = $qery->total_amount - $totalPaymentReceived;
                                ?>
                                <tr>
                                    <td>
                                        <?php
                                        if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') {
                                            ?>
                                            <?php if ($qery->status != 'Cancel') { ?>
                                            <a href="print/invoice.php?id=<?php echo $qery->id; ?>"
                                               target="_blank" title="Print Invoice">
                                                                    <span
                                                                        style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon orange darken-2"><i
                                                                            class="mdi-action-print"></i></span>
                                            </a>
                                        <?php }
                                        if ($qery->status == 'Pending' || $qery->status == 'Draft') { ?>
                                            <a href="invoice_create.php?edit&id=<?php echo $qery->id; ?>"
                                               title="Edit">
                                                                    <span
                                                                        style="width: 50px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon yellow darken-2">Edit</span></a>
                                        <?php }
                                        if ($qery->status == 'Pending') { ?>
                                            <a href="payment_create.php?add&ref=<?php echo $qery->id; ?>"
                                               title="Payment">
                                                                    <span
                                                                        style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon green darken-2">Payment</span>
                                            </a>
                                        <br>
                                            <div class="clearfix"></div>

                                            <a style="margin-left:30px; display: block; cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Paid">
                                                <span
                                                    style="width: 50px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-paid<?= $qery->id ?> mini-stat-icon cyan darken-2">Paid</span>
                                            </a>
                                            <script>
                                                $('.btn-warning-paid<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "You will not be able to change the status again",
                                                            type: "warning",
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been paid!", "success");
                                                            window.location.href = 'invoice.php?paid=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>

                                            <a style="cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Cancel">
                                                                    <span
                                                                        style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                                        class="btn-warning-cancel<?= $qery->id ?> mini-stat-icon deep-orange darken-3">Cancel</span>
                                            </a>
                                        <?php
                                        $PaymentAmount = 0;
                                        $PaymentCode[] = '';
                                        $PaymentCodes = '';
                                        $CancelPayment = '';
                                        $filterPaymentCancel = " WHERE invoice_reference_code = '$qery->id' AND status <> 'Cancel' ";
                                        $CancelPayment = Payment::GetPaymentList($filterPaymentCancel);
                                        if ($CancelPayment) {
                                            foreach ($CancelPayment AS $CancelPaymentRow) {
                                                $PaymentCode[] = $CancelPaymentRow->code;
                                                $PaymentAmount+=$CancelPaymentRow->amount;
                                            }
                                            $PaymentCodes = implode(',', $PaymentCode);
                                        }
                                        if (!$PaymentCodes) { ?>
                                            <script>
                                                $('.btn-warning-cancel<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure change status to cancel?<br>You will not be able to change the status again <br><?php if ($PaymentCodes) {echo '<p>Please delete payments ' . $PaymentCodes . ' against this invoice</p>';}?>",
                                                            type: "warning",
                                                            html: true,
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been cancelled!", "success");
                                                            window.location.href = 'invoice.php?cancel=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>
                                        <?php }else{ ?>
                                            <script>
                                                $('.btn-warning-cancel<?= $qery->id ?>').click(function () {
                                                    swal({
                                                        title: "Are you sure?",
                                                        text: "Are you sure change status to cancel?<br>You will not be able to change the status again <br><?php if ($PaymentCodes) {echo '<p>Please delete payments ' . $PaymentCodes . ' against this invoice</p>';}?>",
                                                        type: "error",
                                                        html: true,
                                                        confirmButtonColor: '#DD6B55',
                                                        closeOnConfirm: false
                                                    });
                                                });
                                            </script>
                                        <?php }
                                        }
                                        else if ($qery->status == 'Draft') { ?>
                                            <!-- Delivered for Draft -->
                                            <a style="cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Validate">
                                                <span
                                                    style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-val<?= $qery->id ?> mini-stat-icon green">Delivered</span>
                                            </a>
                                            <script>
                                                $('.btn-warning-val<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure you want to Mark Delivered?",
                                                            type: "warning",
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your invoice has been Delivered!", "success");
                                                            window.location.href = 'invoice.php?validate=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>

                                            <br>
                                            <a style="margin-left:55px; display:block; cursor:pointer;font-size: 10px;padding: 1px;"
                                               title="Cancel">
                                                <span
                                                    style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-cancel<?= $qery->id ?> mini-stat-icon deep-orange darken-3">Cancel</span>
                                            </a>
                                            <script>
                                                $('.btn-warning-cancel<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure change status to cancel?<br>You will not be able to change the status again.",
                                                            type: "warning",
                                                            html: true,
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been cancelled!", "success");
                                                            window.location.href = 'invoice.php?cancel=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>
                                        <?php }
                                        ?>
                                        <?php } else { ?>
                                            <a href="?edit&id=<?php echo $qery->id; ?>&v"
                                               title="View"><i
                                                    class="fa fa-file-text"></i></a>
                                        <?php } ?>
                                    </td>
                                    <td><?php echo $qery->create_date; ?></td>
                                    <?php
                                    $pyBalance = 0;
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                    ?>
                                    <td><?php echo $qery->code; ?></td>
                                    <td><?php echo $customer->name; ?></td>
                                    <td><?php echo $salesPerson->username; ?></td>
                                    <td><?php echo ($PaymentAmount<$qery->total_amount && $PaymentAmount!=0)?"Partial Paid":$qery->status; ?></td>
                                    <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                    <td><?php echo number_format($totalPaymentReceived, 2, '.', ''); ?></td>
                                    <td><?php echo number_format($qery->total_amount - $totalPaymentReceived, 2, '.', ''); ?></td>
                                </tr>
                                <?php
                            }
                        } ?>
                        </tbody>
                    </table>
                </div>
                <?php
            } // close view
            ?>
        </div>
    </div>
</div>
</div>
<?php include('../includes/inc_footer.php'); ?>

<?php include('../includes/inc_js.php'); ?>
</body>
</html>
