<?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");
require_once("../config/functions.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()) {
            // --- APPROVAL EMAIL NOTIFICATION START ---
            
            // 1. Fetch the transfer details using the transfer ID
            $stmt_td = $con->prepare("SELECT sender, receiver, name, bank, amount, date FROM transfers WHERE id = ?");
            $stmt_td->bind_param("i", $id);
            $stmt_td->execute();
            $transfer_data = $stmt_td->get_result()->fetch_assoc();
            $stmt_td->close();

            if ($transfer_data) {
                // 2. Fetch the customer's email and name using the sender ID
                $sender_id = $transfer_data['sender'];
                $stmt_cd = $con->prepare("SELECT firstname, lastname, email FROM customers WHERE customerid = ?");
                $stmt_cd->bind_param("s", $sender_id);
                $stmt_cd->execute();
                $customer_data = $stmt_cd->get_result()->fetch_assoc();
                $stmt_cd->close();

                if ($customer_data) {
                    // 3. Fetch system settings for bank name and currency
                    $stmt_curr = $con->prepare("SELECT currency, bank_name FROM system_settings LIMIT 1");
                    $stmt_curr->execute();
                    $settings = $stmt_curr->get_result()->fetch_assoc();
                    $stmt_curr->close();
                    
                    $curr_sym = $settings['currency'] ?? '$';
                    $bank_name = $settings['bank_name'] ?? 'Our Bank';
                    
                    // Set up email variables
                    $to_email = $customer_data['email'];
                    $customer_full_name = htmlspecialchars($customer_data['firstname'] . ' ' . $customer_data['lastname']);
                    $formatted_amount = $curr_sym . number_format($transfer_data['amount'], 2);
                    $current_year = date('Y');
          
                    $txnRef = 'TXN-APP' . rand(1000000, 9999999);
                    
                    $subject = "Transfer Approved: " . $formatted_amount . " Processed Successfully";
                    
                    $body = "
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <meta charset='UTF-8'>
                        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
                    </head>
                    <body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f8fafc;'>
                        <table width='100%' cellpadding='0' cellspacing='0' style='background-color: #f8fafc; padding: 40px 20px;'>
                            <tr>
                                <td align='center'>
                                    <table width='100%' cellpadding='0' cellspacing='0' style='max-width: 600px; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05);'>
                                        <tr>
                                            <td style='background: linear-gradient(135deg, #003399 0%, #005D9D 100%); padding: 30px; text-align: center;'>
                                                <h1 style='color: #ffffff; margin: 0; font-size: 24px; font-weight: bold;'>Transfer Approved</h1>
                                            </td>
                                        </tr>
                                        
                                        <tr>
                                            <td style='padding: 40px 30px; color: #0f172a; line-height: 1.6;'>
                                                <h2 style='margin-top: 0; color: #003399; font-size: 20px;'>Hello $customer_full_name,</h2>
                                                <p style='font-size: 16px; color: #64748b;'>Great news! Your pending transfer has been officially approved and processed by our administration team.</p>
                                                
                                                <div style='background-color: #e6efff; border-left: 4px solid #003399; padding: 20px; margin: 30px 0; border-radius: 0 8px 8px 0;'>
                                                    <h3 style='margin-top: 0; color: #003399; font-size: 16px; text-transform: uppercase; letter-spacing: 1px;'>Transfer Details</h3>
                                                    <table width='100%' cellpadding='8' cellspacing='0' style='font-size: 15px;'>
                                                        <tr>
                                                            <td width='40%' style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Amount:</td>
                                                            <td style='color: #0f172a; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>$formatted_amount</td>
                                                        </tr>
                                                        <tr>
                                                            <td style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Beneficiary:</td>
                                                            <td style='color: #0f172a; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>" . htmlspecialchars($transfer_data['name']) . "</td>
                                                        </tr>
                                                        <tr>
                                                            <td style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Account Number:</td>
                                                            <td style='color: #0f172a; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>" . htmlspecialchars($transfer_data['receiver']) . "</td>
                                                        </tr>
                                                        <tr>
                                                            <td style='color: #64748b; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Destination Bank:</td>
                                                            <td style='color: #0f172a; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>" . htmlspecialchars($transfer_data['bank']) . "</td>
                                                        </tr>
                                                        <tr>
                                                            <td style='color: #198754; font-weight: bold; border-bottom: 1px solid #cce0ff;'>Status:</td>
                                                            <td style='color: #198754; font-weight: bold; border-bottom: 1px solid #cce0ff; text-align: right;'>Approved</td>
                                                        </tr>
                                                        <tr>
                                                            <td style='color: #64748b; font-weight: bold;'>Reference ID:</td>
                                                            <td style='color: #0f172a; font-weight: bold; text-align: right;'>$txnRef</td>
                                                        </tr>
                                                    </table>
                                                </div>
                                                
                                                <p style='font-size: 16px; color: #64748b; margin-top: 30px;'>If you have any questions, please contact our support team .</p>
                                                <p style='font-size: 16px; color: #64748b;'>Thank you for banking with us,<br><strong style='color: #003399;'>The $bank_name Team</strong></p>
                                            </td>
                                        </tr>
                                        
                                        <tr>
                                            <td style='background-color: #f1f5f9; text-align: center; padding: 20px; font-size: 13px; color: #94a3b8;'>
                                                <p style='margin: 0;'>&copy; $current_year $bank_name. All rights reserved.</p>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </body>
                    </html>
                    ";
                    
                    // Call your custom mail function
                    sendMail($to_email, $subject, $body);
                }
            }
            // --- APPROVAL EMAIL NOTIFICATION END ---

            $_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>