<?php
ini_set('session.gc_maxlifetime', 360000);
session_set_cookie_params(360000);
session_start(); 
$datetoday = date('Y-m-d h:i:a'); 

require_once('../connect.php');
require_once('sql_required.php');

$accountNo = isset($_GET['account_no']) ? $_GET['account_no'] : '';

$limit = 10; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

$totalQuery = $conn->query("SELECT COUNT(*) AS total FROM tbl_bigasrecord WHERE unique_id LIKE '$accountNo' and transaction_type ='order'");
$totalRow = $totalQuery->fetch_assoc();
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $limit);

$query = "SELECT * FROM tbl_bigasrecord WHERE unique_id LIKE '$accountNo' and transaction_type ='order'  ORDER BY date_purchase  ";
$result = $conn->query($query);
 
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bigas Records</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<div class="container mt-5">
    <h2 class="text-center">Bigas Payment Records</h2> 
    <center><a href="bigasallrecords.php"> View All </a></center>
    <hr>
    <div class="d-flex justify-content-between mb-3">
        <h4>Account No: <span class="text-primary"><?= htmlspecialchars($accountNo) ?></span></h4>
        <a href="index.php" class="btn btn-secondary">Back</a>
    </div>

    <table  style="font-size: 12px;" id="example1"  class="table table-striped table-bordered table-sm table-hover" cellspacing="0" width="100%">
			 
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Rice Type</th>
                <th>Quantity (kg)</th>
                <th>Amount (₱)</th>
                <th>Date Purchased</th>
                <th>Payment Due</th>
                <th>Payment Status</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php $count = $start + 1; ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= $count++ ?></td>
                        <td><?= htmlspecialchars($row['rice_type']) ?></td>
                        <td><?= htmlspecialchars($row['quantity_kilo']) ?> kg</td>
                        <td>₱<?= number_format($row['bigas_credit_amount'], 2) ?></td>
                        <td><?= date('M d, Y', strtotime($row['date_purchase'])) ?></td>
                        <td><?= date('M d, Y', strtotime($row['payment_due'])) ?></td>
                        <td>
                            <?php if (empty($row['payment_option'])): ?>
                                <button class="btn btn-primary btn-sm pay-btn"
                                        data-bs-toggle="modal"
                                        data-bs-target="#payModal"
                                        data-id="<?= $row['id'] ?>"
                                        data-uniqueid="<?= $row['unique_id'] ?>"
                                        data-ricetype="<?= htmlspecialchars($row['rice_type']) ?>"
                                        data-quantity="<?= $row['quantity_kilo'] ?>"
                                        data-datepurchase="<?= $row['date_purchase'] ?>"
                                        data-paymentdue="<?= $row['payment_due'] ?>"
                                        data-amount="<?= $row['bigas_credit_amount'] ?>"
                                        data-reference="<?= $row['reference_code'] ?>">
                                    PAY
                                </button>
                            <?php else: ?>
                                <span class="badge bg-success">Paid</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center">No records found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="payModal" tabindex="-1" aria-labelledby="payModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="payModalLabel">Pay Now</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form method="POST">
                    <input type="hidden" name="unique_id" id="modalUniqueId">
                    <input type="hidden" name="rice_type" id="modalRiceType">
                    <input type="hidden" name="quantity_kilo" id="modalQuantity">
                    <input type="hidden" name="date_purchase" id="modalDatePurchase">
                    <input type="hidden" name="payment_due" id="modalPaymentDue">
                    
                    <div class="mb-3">
                        <label class="form-label">Reference Code</label>
                        <input type="text" class="form-control" id="modalReference" name="reference_code" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount Due (₱)</label>
                        <input type="text" class="form-control" id="modalAmount" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Enter Amount</label>
                        <input type="number" class="form-control" name="payAmount" required min="1">
                    </div>
                    <button type="submit" class="btn btn-success w-100">Submit Payment</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
$(document).on("click", ".pay-btn", function() {
    $("#modalUniqueId").val($(this).data("uniqueid"));
    $("#modalRiceType").val($(this).data("ricetype"));
    $("#modalQuantity").val($(this).data("quantity"));
    $("#modalDatePurchase").val($(this).data("datepurchase"));
    $("#modalPaymentDue").val($(this).data("paymentdue"));
    $("#modalReference").val($(this).data("reference"));
    $("#modalAmount").val($(this).data("amount"));
});
</script>

</body>
</html>
<script>
$(document).ready(function () {
    $(".pay-btn").on("click", function () {
        $("#modalUniqueId").val($(this).data("uniqueid"));
        $("#modalRiceType").val($(this).data("ricetype"));
        $("#modalQuantity").val($(this).data("quantity"));
        $("#modalDatePurchase").val($(this).data("datepurchase"));
        $("#modalPaymentDue").val($(this).data("paymentdue"));
        $("#modalReference").val($(this).data("reference"));
        $("#modalAmount").val($(this).data("amount"));
    });

    $("form").on("submit", function (e) {
        e.preventDefault();

        let formData = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "process_bigaspay.php",
            data: formData,
            dataType: "json",
            success: function (response) {
                if (response.status === "success") {
                    Swal.fire({
                        icon: "success",
                        title: response.message,
                        text: "Your payment has been recorded.",
                        confirmButtonColor: "#3085d6",
                        confirmButtonText: "OK"
                    }).then(() => {
                        $("#payModal").modal("hide");
                        $("button[data-reference='" + response.reference_code + "']")
                            .replaceWith('<span class="badge bg-success">Paid</span>');
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        title: "Payment Failed!",
                        text: response.message,
                        confirmButtonColor: "#d33",
                        confirmButtonText: "OK"
                    });
                }
            }
        });
    });
});
</script>
