<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = '';
$dateto = '';
$tax_category = '';
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
/*if (isset($_POST) && !empty($_GET['cancel'])) {
    //exit;
    $data['status'] = 'Cancel';
    $data['cancel_date'] = 'Now()';
    Purpayment::UpdatePurpaymentSetup($_GET['cancel'], $data);
    header("Location: " . PROJECT_ADMIN_URL . "purpayment.php?view");
    exit();
} */

if (isset($_POST) && !empty($_GET['cancel'])) {
    // Step 1: Update payment status to "Cancel"
    $data['status'] = 'Cancel';
    $data['cancel_date'] = 'NOW()';
    $result = Purpayment::UpdatePurpaymentSetup($_GET['cancel'], $data);

    // Step 2: Retrieve the purchase reference ID from the payment
    $payment = Purpayment::GetPurpaymentSetupById($_GET['cancel']);
    $purchaseReferenceId = $payment->purchase_reference_code;

    // Step 3: Revert the purchase status to "Pending" if a reference exists
    if (!empty($purchaseReferenceId)) {
        $purchaseUpdateData = [
            'status' => 'Pending', // Revert status to Pending
        ];
        $updateResult = PurchaseSetup::UpdatePurchaseSetup($purchaseReferenceId, $purchaseUpdateData);

       
    }

    // Redirect to prevent duplicate submissions
    header("Location: " . PROJECT_ADMIN_URL . "purpayment.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();
}
// Get the current year and month
$currentYear = date('Y');
$currentMonth = date('m');

// If today is before July, adjust the year to the previous year
if ($currentMonth < 7) {
    $currentYear--;
}
extract($_REQUEST);
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime($currentYear . '-07-01'));
} 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 = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' ";
if (!empty($supplier_id) && $supplier_id !== "All") {
    $supplier_id = intval($supplier_id); // Sanitize input
    $filter .= " AND supplier_id = $supplier_id"; // Add supplier filter
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <style>
        .fa-arrows-alt:before {
            margin-right: 5px;
        }
        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>Purchase Payments</h3>
            </div>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true, // Creates a dropdown to control month
                        selectYears: true, // Creates a dropdown to control year
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true, // Creates a dropdown to control month
                        selectYears: true, // Creates a dropdown to control year
                    });
                });
            </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="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="form-control"/>
                        </td>
                       <td class="col s4">Supplier<br>
                            <?php
                            // Fetch suppliers from your SupplierSetup table
                            $suppliers = SupplierSetup::GetSupplierSetupList();
                            ?>
                            <select class="form-control" required id="supplier_id"
                                    name="supplier_id">
                                <option>All</option>
                                <?php
                                if ($suppliers) {
                                    foreach ($suppliers as $supplier) {
                                        echo '<option ';
                                        if ($supplier->id == $supplier_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $supplier->id . '" >' . $supplier->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 btn-secondary waves-effect waves-dark" style="float:right;margin-left:5px; background-color: #800080;"
                       href="purpayment_create.php?add">Add Supplier Payment <i
                            class="mdi-content-add-box"></i></a>
          			<a class="btn btn-success waves-effect waves-light" style="float:right;margin-left:5px; background-color: #008000;"
                       href="purpayment_tax_create.php?add">Add Tax Paymnent <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="responsive-table display">
                        <thead>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Supplier</th>
                          	<th style="text-align: right;">Purchase Reference</th>
                            <th style="text-align: right;">Invoice Amount</th>
                          	<th style="text-align: right;">Payment Type</th>
                          	<th style="text-align: right;">CPR</th>
                          	<th style="text-align: right;">Amount Paid</th>
                        <!--    <th>Payment Type</th> -->
                            <th>Cheque No./Date</th>
                           <!--   <th>Account Number</th>  -->
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Supplier</th>
                          	<th style="text-align: right;">Purchase Reference</th>
                            <th style="text-align: right;">Invoice Amount</th>
                          	<th style="text-align: right;">Payment Type</th>
                          	<th style="text-align: right;">CPR</th>
                          	<th style="text-align: right;">Amount Paid</th>
                        <!--     <th>Payment Type</th> -->
                            <th>Cheque No./Date</th>
                         <!--   <th>Account Number</th>  -->
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = Purpayment::GetPurpaymentList($filter);
                        if ($qry) {
                            foreach ($qry as $qery) {
                                ?>
                                <tr>
                                    <td>
                                        <?php if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') {
                                      
                                                    $editUrl = ($qery->supplier_payment_type == 'supplier') ? 
                                                     'purpayment_create.php?edit&id=' . $qery->id : 
                                                     'purpayment_tax_create.php?edit&id=' . $qery->id;
                                      	?>
                   							<a href="<?php echo $editUrl; ?>" title="Edit">
                                          
                                                                <span
                                                                    style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                                                    class="mini-stat-icon orange">
                                                                    <i class="mdi-image-edit"></i>
                                                                </span>
                                            </a>
                                            <a style="cursor:pointer;font-size: 10px;padding: 1px;" data-toggle="modal"
                                               data-target="#myModalCancel<?= $qery->id ?>" title="Cancel">
                                                <span
                                                    style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-confirm<?= $qery->id ?> mini-stat-icon deep-orange darken-3"><i
                                                        class="fa fa-arrows-alt">Cancel</i></span>
                                            </a>
                                            <script>
                                                $('.btn-warning-confirm<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure change status to cancel?",
                                                            type: "warning",
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been cancelled!", "success");
                                                            window.location.href = 'purpayment.php?cancel=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>
                                        <?php } ?>
                                    </td>
                                    <td><?php echo date("d-m-Y", strtotime($qery->create_date)); ?></td>
                                    <?php
                                    $supplier = SupplierSetup::GetSupplierSetupById($qery->supplier_id);
                                    $bank = BankSetup::GetBankSetupById($qery->bank_name);
                              		$purchase = PurchaseSetup::GetPurchaseSetupById($qery->purchase_reference_code);
                                    ?>
                                    <td><?php echo $supplier->name; ?></td>
                                  	<td style="text-align: right;">
                                        <?php if (empty($qery->purchase_reference_code)) { ?>
                                            <a href="add_purchase_reference.php?payment_id=<?php echo $qery->id; ?>" 
                                               class="btn btn-small waves-effect waves-light">
                                                Add Reference
                                            </a>
                                        <?php } else { 
                                            echo $purchase->purchase_invoice_no;
                                        } ?>
                                    </td>
                                    <td style="text-align: right;"><?php echo number_format($qery->amount, 2); ?></td>
                                    <td style="text-align: right;"><?php echo $qery->supplier_payment_type; ?></td>
                                  	<td style="text-align: right;"><?php echo $qery->cpr; ?></td>
                                    <td style="text-align: right;"><?php echo number_format($qery->amount_payable); ?></td>

                                 <!--   <td><?php echo $qery->payment_type; ?></td> -->
                                    <td><?php
                                        if ($qery->payment_type == 'party') {
                                            echo 'Party: ' . $qery->party_name . " - " . $qery->cheque_number . "<br>";
                                            echo 'Cheque Details: ' . $qery->cheque_payee_name . " (" . $qery->cheque_bank_name . " - " . date('d-m-Y', strtotime($qery->cheque_date)) . ")";
                                        } else if ($qery->payment_type == 'online') {
                                            echo "From: " . $qery->from_bank_name . "<br>";
                                            echo 'To: ' . $bank->bank_name;
                                        } else {
                                            
                                            if ($qery->payment_type == 'bank') {
                                                echo  $qery->cheque_number . " - " . date('d-m-Y', strtotime($qery->cheque_date)) ;
                                              //  echo   " - " . date('d-m-Y', strtotime($qery->cheque_date)) ;
                                            }
                                        } ?></td>
                                 <!--   <td><?php echo $qery->bank_account_number; ?></td> -->
                                </tr>
                                <?php
                            }
                        } ?>
                        </tbody>
                    </table>
                </div>
                <?php

            } // close view
            ?>
          <div id="purchaseReferenceModal" class="modal">
    <div class="modal-content">
        <h4>Add Purchase Reference</h4>
        <form id="updatePurchaseReferenceForm">
            <input type="hidden" id="paymentId" name="payment_id">
            <div class="input-field">
                <label for="purchase_reference_code">Select Reference</label>
                <select id="purchase_reference_code_modal" name="purchase_reference_code" class="browser-default">
                    <option value="" disabled selected>Select Purchase Reference</option>
                    <?php
                    $purchaseList = PurchaseSetup::GetPurchaseSetupList();
                    if ($purchaseList) {
                        foreach ($purchaseList as $purchase) {
                            echo '<option value="' . $purchase->id . '">' . $purchase->purchase_invoice_no . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
            <button type="button" class="btn waves-effect waves-light" onclick="savePurchaseReference()">Save</button>
        </form>
    </div>
</div>

        </div>
    </div>
</div>
</div>
<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>
 <script>
   document.addEventListener("DOMContentLoaded", function () {
    const table = document.querySelector("#data-table-simple tbody");

    if (table) {
        const rows = Array.from(table.rows);

        // Sort rows by the date in the second column (index 1)
        rows.sort((a, b) => {
            const dateA = parseDate(a.cells[1].textContent.trim());
            const dateB = parseDate(b.cells[1].textContent.trim());
            return dateB - dateA; // Ascending order
        });

        // Remove existing rows and append sorted rows
        table.innerHTML = "";
        rows.forEach(row => table.appendChild(row));
    }

    // Function to parse `dd-mm-yyyy` to a Date object
    function parseDate(dateString) {
        const [day, month, year] = dateString.split("-").map(Number);
        return new Date(year, month - 1, day); // Note: Month is 0-indexed
    }
});

</script>

</body>
</html>