<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");
include("fetch_settings.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

// Pagination setup
$records_per_page = 10;
$current_page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($current_page - 1) * $records_per_page;

// Handle form submissions first
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["approve"])) {
        $id = intval($_POST["approve"]);
        $stmt_approve = $con->prepare("UPDATE transfers SET status = 1 WHERE id = ?");
        $stmt_approve->bind_param('i', $id);
        if ($stmt_approve->execute()) {
            // Store message in session instead of a local variable
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Cash Transfer Has Been Approved! Please ensure you have credited the account number'];
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Error approving transfer: ' . $con->error];
        }
        $stmt_approve->close();
    }

    if (isset($_POST["backdate"])) {
        $newDateTime = htmlspecialchars($_POST['new_datetime']);
        $id = intval($_POST['id']);
        $stmt_backdate = $con->prepare("UPDATE transfers SET date = ? WHERE id = ?");
        $stmt_backdate->bind_param('si', $newDateTime, $id);
        if ($stmt_backdate->execute()) {
            $_SESSION['message'] = ['type' => 'success', 'text' => 'The transfer date and time have been updated successfully'];
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'Unable to update the date and time: ' . $con->error];
        }
        $stmt_backdate->close();
    }
    // Redirect to the same page to prevent form resubmission
    header("Location: pendingtransfer.php");
    exit;
}

// Get total number of pending transfers
$total_count_query = $con->prepare("SELECT COUNT(*) AS total FROM transfers WHERE status = 0");
$total_count_query->execute();
$total_count_result = $total_count_query->get_result();
$total_records = $total_count_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$total_count_query->close();

// Fetch pending transfers with pagination
$transfers = [];
$stmt = $con->prepare("SELECT * FROM transfers WHERE status = 0 ORDER BY date DESC LIMIT ? OFFSET ?");
$stmt->bind_param('ii', $records_per_page, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $transfers[] = $row;
}
$stmt->close();

// Fetch currency from system settings
$currency = '$';
$stmt_currency = $con->prepare("SELECT currency FROM system_settings LIMIT 1");
$stmt_currency->execute();
$result_currency = $stmt_currency->get_result();
if ($row_currency = $result_currency->fetch_assoc()) {
    $currency = htmlspecialchars($row_currency['currency']);
}
$stmt_currency->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Pending Transfers</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <meta name="description" content="">

    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">

    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>

<body>

<main>
    
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">
    
            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">Pending Transfer</h1>
                    </div>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">Pending Transfers</h5>
                </div>

                <div class="card-body">
                    <?php if (isset($_SESSION['message'])): 
                        $message = $_SESSION['message'];
                        // Unset the session variable after retrieving its value
                        unset($_SESSION['message']);
                    ?>
                        <script>
                            // Wait for the DOM to be fully loaded before firing SweetAlert
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    title: '<?= $message['type'] === 'success' ? 'Successful!' : 'Error!'; ?>',
                                    text: '<?= $message['text']; ?>',
                                    icon: '<?= $message['type']; ?>',
                                    confirmButtonText: 'OK'
                                });
                            });
                        </script>
                    <?php endif; ?>
                    
                    <div class="bg-light rounded p-3 d-none d-lg-block">
                        <div class="row g-4">
                            <div class="col-lg-2"><h6 class="mb-0">Receiver's Name</h6></div>
                            <div class="col-lg-2"><h6 class="mb-0">Receiver's Bank</h6></div>
                            <div class="col-lg-2"><h6 class="mb-0">Bank Address</h6></div>
                            <div class="col-lg-2"><h6 class="mb-0">Account No</h6></div>
                            <div class="col-lg-2"><h6 class="mb-0">Amount</h6></div>
                            <div class="col-lg-2"><h6 class="mb-0">Date & Action</h6></div>
                        </div>
                    </div>

                    <?php if (!empty($transfers)): ?>
                        <?php foreach ($transfers as $transfer): ?>
                            <div class="row g-4 align-items-center border-bottom px-2 py-4">
                                <div class="col-12 col-lg-2">
                                    <h6 class="mb-0 fw-normal">
                                        <span class="d-lg-none">Receiver's Name: </span>
                                        <?= htmlspecialchars($transfer['name']); ?>
                                    </h6>
                                </div>
                                <div class="col-12 col-lg-2">
                                    <h6 class="mb-0 fw-normal">
                                        <span class="d-lg-none">Receiver's Bank: </span>
                                        <?= htmlspecialchars($transfer['bank']); ?>
                                    </h6>
                                </div>
                                <div class="col-12 col-lg-2">
                                    <h6 class="mb-0 fw-normal">
                                        <span class="d-lg-none">Bank Address: </span>
                                        <?= htmlspecialchars($transfer['address']); ?>
                                    </h6>
                                </div>
                                <div class="col-12 col-lg-2">
                                    <h6 class="mb-0 fw-normal">
                                        <span class="d-lg-none">Account No: </span>
                                        <?= htmlspecialchars($transfer['receiver']); ?>
                                    </h6>
                                </div>
                                <div class="col-12 col-lg-2">
                                    <h6 class="mb-0 fw-normal">
                                        <span class="d-lg-none">Amount: </span>
                                        <?= $currency . ' ' . number_format($transfer['amount'], 2); ?>
                                    </h6>
                                </div>
                                <div class="col-12 col-lg-2">
                                    <h6 class="mb-0 fw-normal">
                                        <span class="d-lg-none">Date: </span>
                                        <?= htmlspecialchars($transfer['date']); ?>
                                    </h6>
                                    <form method="post" action="" class="d-inline-block mt-2">
                                        <input hidden value="<?= $transfer['id']; ?>" name="approve">
                                        <button type="submit" class="btn btn-sm btn-primary-soft" name="pay">Approve</button>
                                    </form>
                                    <button class="btn btn-sm btn-info-soft mt-2" data-bs-toggle="modal" data-bs-target="#backdateModal-<?= $transfer['id']; ?>">Backdate</button>
                                </div>
                            </div>
                            
                            <div class="modal fade" id="backdateModal-<?= $transfer['id']; ?>" tabindex="-1" aria-labelledby="backdateModalLabel-<?= $transfer['id']; ?>" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="backdateModalLabel-<?= $transfer['id']; ?>">Backdate Transfer</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <form method="post" action="">
                                                <div class="mb-3">
                                                    <label for="new_datetime-<?= $transfer['id']; ?>" class="form-label">Select New Date</label>
                                                    <input type="text" class="form-control datetimepicker" id="new_datetime-<?= $transfer['id']; ?>" name="new_datetime" required>
                                                    <input type="hidden" name="id" value="<?= $transfer['id']; ?>">
                                                </div>
                                                <button type="submit" class="btn btn-primary" name="backdate">Update Date & Time</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="row px-2 py-4 text-center">
                            <div class="col">
                                <p class="mb-0">No pending transfers found</p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="card-footer pt-0">
                    <div class="d-sm-flex justify-content-sm-between align-items-sm-center">
                        <p class="mb-sm-0 text-center text-sm-start">
                            Showing <?= $offset + 1 ?> to <?= min($offset + $records_per_page, $total_records) ?> of <?= $total_records ?> entries
                        </p>

                        <nav class="mb-sm-0 d-flex justify-content-center" aria-label="navigation">
                            <ul class="pagination pagination-sm pagination-primary-soft mb-0">
                                <li class="page-item <?= ($current_page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= max(1, $current_page - 1) ?>">Previous</a>
                                </li>

                                <?php
                                $visible_pages = 3;
                                $start_page = max(1, $current_page - floor($visible_pages / 2));
                                $end_page = min($total_pages, $start_page + $visible_pages - 1);

                                if ($end_page - $start_page + 1 < $visible_pages) {
                                    $start_page = max(1, $end_page - $visible_pages + 1);
                                }

                                if ($start_page > 1) {
                                    echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                                    if ($start_page > 2) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                }

                                for ($i = $start_page; $i <= $end_page; $i++) {
                                    echo '<li class="page-item ' . ($i == $current_page ? 'active' : '') . '">';
                                    echo '<a class="page-link" href="?page=' . $i . '">' . $i . '</a>';
                                    echo '</li>';
                                }

                                if ($end_page < $total_pages) {
                                    if ($end_page < $total_pages - 1) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                    echo '<li class="page-item ' . ($total_pages == $current_page ? 'active' : '') . '">';
                                    echo '<a class="page-link" href="?page=' . $total_pages . '">' . $total_pages . '</a>';
                                    echo '</li>';
                                }
                                ?>

                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?page=<?= min($total_pages, $current_page + 1) ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
    
        </div>
    </div>
</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script src="assets/js/functions.js"></script>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        flatpickr('.datetimepicker', {
            enableTime: true,
            time_24hr: true,
            enableSeconds: true,
            dateFormat: 'Y-m-d H:i:S'
        });
    });
</script>

</body>
</html>