<?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);

// Required PHPMailer includes (paths should match process_shipment.php)
require_once 'vendor/PHPMailer/src/Exception.php';
require_once 'vendor/PHPMailer/src/PHPMailer.php';

require_once '../config.php';
require_once '../get_setting.php'; 

// Load the core functions including send_email_notification()
require_once '../include/email_core_functions.php'; 

// Load the new email functions
require_once '../include/get_payment_status_email_body.php';
require_once '../include/send_mail_wrapper.php';



if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: admin_login.php");
    exit;
}

if (isset($_GET['logout'])) {
    session_destroy();
    header("location: admin_login.php");
    exit;
}


require_once '../config.php';

// --- START APPROVE/DECLINE LOGIC ---
if (isset($_GET['action']) && isset($_GET['proof_id']) && is_numeric($_GET['proof_id'])) {
    $action = $_GET['action'];
    $proof_id = (int)$_GET['proof_id'];
    $status_success = false;
    $status_error = "";
    
    // --- 0. PRE-TRANSACTION: Fetch all necessary data for email and updates ---
    try {
        $sql_fetch_data = "
            SELECT 
            pp.*, 
            s.tracking_number, 
            s.receiver_email AS email, 
            s.receiver_name AS user_name
            FROM 
            payment_proofs pp
            JOIN 
            shipments s ON pp.shipment_id = s.id
            WHERE 
            pp.proof_id = :id
        ";
        $stmt_fetch_data = $pdo->prepare($sql_fetch_data);
        $stmt_fetch_data->bindParam(':id', $proof_id, PDO::PARAM_INT);
        $stmt_fetch_data->execute();
        $proof_data = $stmt_fetch_data->fetch(PDO::FETCH_ASSOC);

        if ($proof_data) {
            $shipment_id = $proof_data['shipment_id'];
            $recipient_email = $proof_data['email'];
            $email_status = ($action === 'approve') ? 'Approved' : 'Declined';
            
            // Prepare a clean array for the email function
            $email_data = [
                'proof_id' => $proof_data['proof_id'],
                'tracking_number' => $proof_data['tracking_number'],
                'amount' => $proof_data['amount'],
                'payment_method' => $proof_data['payment_method'],
                'user_name' => $proof_data['user_name'],
            ];


            $pdo->beginTransaction();

            if ($action === 'approve') {
                // A. Update the payment_proofs status
                $sql_proof_update = "UPDATE payment_proofs SET proof_status = 'Approved' WHERE proof_id = :id";
                $stmt_proof_update = $pdo->prepare($sql_proof_update);
                $stmt_proof_update->bindParam(':id', $proof_id, PDO::PARAM_INT);
                $stmt_proof_update->execute();

                // B. Update the shipments status to 'paid'
                $sql_shipment_update = "UPDATE shipments SET payment_status = 'Paid' WHERE id = :shipment_id";
                $stmt_shipment_update = $pdo->prepare($sql_shipment_update);
                $stmt_shipment_update->bindParam(':shipment_id', $shipment_id, PDO::PARAM_INT);
                $stmt_shipment_update->execute();
                
                $status_success = true;
                $status_message = "Payment proof **approved** and Shipment #{$shipment_id} marked as **Paid**.";

            } elseif ($action === 'decline') {
                // A. Update the payment_proofs status to Declined
                $sql_proof_update = "UPDATE payment_proofs SET proof_status = 'Declined' WHERE proof_id = :id";
                $stmt_proof_update = $pdo->prepare($sql_proof_update);
                $stmt_proof_update->bindParam(':id', $proof_id, PDO::PARAM_INT);
                $stmt_proof_update->execute();
                
                $status_success = true;
                $status_message = "Payment proof **declined**. User can now resubmit a new proof.";
            } else {
                $status_error = "Invalid action specified.";
            }
            
            if ($status_success) {
                $pdo->commit();
                

                
            } 
            // *** FIX APPLIED: The unnecessary else { $pdo->rollBack(); } has been removed. ***

        } else {
            $status_error = "Payment proof record not found.";
        }
    } catch (PDOException $e) {
        // This is the correct place to handle the rollback if a DB operation failed.
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $status_error = "Database transaction error: " . $e->getMessage();
    }
    
    // ... rest of the redirect logic ...
    $redirect_url = "payment_proofs.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1);
    
    
    if ($status_success) {
        $redirect_url .= "&status=success&msg=" . urlencode($status_message);
    } elseif ($status_error) {
        $redirect_url .= "&status=error&msg=" . urlencode($status_error);
    }
    header("Location: " . $redirect_url);
    exit;
}
// --- END APPROVE/DECLINE LOGIC ---

$records_per_page = 4;

$total_records_sql = "SELECT COUNT(proof_id) FROM payment_proofs"; 
$total_records_stmt = $pdo->query($total_records_sql);
$total_records = $total_records_stmt->fetchColumn();

$total_pages = ceil($total_records / $records_per_page);

$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;

if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
}
if ($page < 1) {
    $page = 1;
}

$offset = ($page - 1) * $records_per_page;

$proofs = [];

$sql = "SELECT * FROM payment_proofs ORDER BY submission_date DESC LIMIT :limit OFFSET :offset";

if ($stmt = $pdo->prepare($sql)) {
    $stmt->bindValue(':limit', (int) $records_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int) $offset, PDO::PARAM_INT);

    if ($stmt->execute()) {
        $proofs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        echo "Oops! Something went wrong. Please try again later.";
    }
    unset($stmt);
}


// --- START DELETE LOGIC ---
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    $delete_success = false;
    $delete_error = "";
    
    try {
        
        $sql_select = "SELECT * FROM payment_proofs WHERE proof_id = :id";
        $stmt_select = $pdo->prepare($sql_select);
        $stmt_select->bindParam(':id', $delete_id, PDO::PARAM_INT);
        $stmt_select->execute();
        $proof_data = $stmt_select->fetch(PDO::FETCH_ASSOC);

        if ($proof_data) {
            
            $file_paths = [];
            
            
            if (!empty($proof_data['bank_proof_path'])) $file_paths[] = '../' . $proof_data['bank_proof_path'];
            if (!empty($proof_data['crypto_proof_path'])) $file_paths[] = '../' . $proof_data['crypto_proof_path'];
            if (!empty($proof_data['giftcard_proof_front_path'])) $file_paths[] = '../' . $proof_data['giftcard_proof_front_path'];
            if (!empty($proof_data['giftcard_proof_back_path'])) $file_paths[] = '../' . $proof_data['giftcard_proof_back_path'];

            
            $sql_delete = "DELETE FROM payment_proofs WHERE proof_id = :id";
            $stmt_delete = $pdo->prepare($sql_delete);
            $stmt_delete->bindParam(':id', $delete_id, PDO::PARAM_INT);
            $stmt_delete->execute();

            
            foreach ($file_paths as $path) {
                if (file_exists($path)) {
                    unlink($path);
                }
            }
            
            $delete_success = true;
            
        } else {
            $delete_error = "Record not found.";
        }
    } catch (PDOException $e) {
        $delete_error = "Database error: " . $e->getMessage();
    }
    
    
    $redirect_url = "payment_proofs.php?page=" . $page;
    if ($delete_success) {
        $redirect_url .= "&status=deleted";
    } elseif ($delete_error) {
        $redirect_url .= "&status=error&msg=" . urlencode($delete_error);
    }
    header("Location: " . $redirect_url);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Payment Proofs</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php if ($use_favicon): ?>
    <link rel="icon" type="<?php echo $favicon_mime; ?>" href="../<?php echo $favicon_path; ?>">
    <?php endif; ?>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/font-awesome-pro.css">
</head>
<body>

    <?php include "nav.php" ?>
    
    <div id="wrapper">
        
        <?php include "header.php" ?>

        <div class="main-content-wrapper">
            <div id="main-content" class="container-fluid">
                <h4 class="fw-bolder mb-4">Payment Proofs for Review</h4>
                <?php if (isset($_GET['status'])): ?>
    <?php if ($_GET['status'] == 'deleted'): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            Payment proof **successfully deleted** from the database and all associated files were removed.
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php elseif ($_GET['status'] == 'success' && isset($_GET['msg'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars(urldecode($_GET['msg'])); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php elseif ($_GET['status'] == 'error' && isset($_GET['msg'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            **Error:** <?php echo htmlspecialchars(urldecode($_GET['msg'])); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    <?php endif; ?>
                
                <div class="card-enhanced border-0">
                    <div class="card-header border-0 d-flex justify-content-between align-items-center py-3 px-4">
                        <div class="d-flex align-items-center">
                            <span>Showing Records <?php echo $offset + 1; ?>-<?php echo min($offset + $records_per_page, $total_records); ?></span>
                        </div>
                        <div class="d-flex align-items-center">
                            <span class="text-muted me-2 small">Total:</span>
                            <span class="badge bg-primary rounded-pill"><?php echo $total_records; ?></span>
                        </div>
                    </div>
                    
                    <div class="card-body">
                        <?php if (!empty($proofs)): ?>
                        <div class="table-responsive">
                            <table class="table-enhanced table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th scope="col">No.</th>
                                        <th scope="col">Tracking No.</th>
                                        <th scope="col">Status</th>
                                        <th scope="col">Method</th>
                                        <th scope="col">Amount (USD)</th>
                                        <th scope="col">Submission Date</th>
                                        <th scope="col">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    // Initialize a counter to start from 1 for each page
                                    $row_number = $offset + 1;
                                    foreach ($proofs as $proof): 
                                        $proof_status = htmlspecialchars($proof['proof_status']);
                                        $is_pending = $proof_status === 'Pending Review';
                                        
                                        $status_class = 'bg-secondary';
                                        if ($proof_status === 'Approved') $status_class = 'bg-success';
                                        if ($proof_status === 'Declined') $status_class = 'bg-danger';
                                        if ($proof_status === 'Pending Review') $status_class = 'bg-warning text-dark';
                                    ?>
                                    <tr>
                                        <td><?php echo $row_number++; ?></td> 
                                        <td><a href="shipment_details.php?id=<?php echo $proof['shipment_id']; ?>" class="fw-bold text-decoration-none"><?php echo htmlspecialchars($proof['tracking_number']); ?></a></td>
                                        <td><span class="badge <?php echo $status_class; ?>"><?php echo $proof_status; ?></span></td>
                                        <td>
                                            <?php 
                                                $method = htmlspecialchars($proof['payment_method']);
                                                $badge_class = '';
                                                switch ($method) {
                                                    case 'bank': $badge_class = 'bg-info'; break;
                                                    case 'crypto': $badge_class = 'bg-warning text-dark'; break;
                                                    case 'giftcard': $badge_class = 'bg-success'; break;
                                                    default: $badge_class = 'bg-secondary'; break;
                                                }
                                            ?>
                                            <span class="badge <?php echo $badge_class; ?>"><?php echo ucfirst($method); ?></span>
                                        </td>
                                        <td>$<?php echo number_format($proof['amount'], 2); ?></td>
                                        <td><?php echo date('M d, Y, g:i A', strtotime($proof['submission_date'])); ?></td>
                                        <td class="d-inline-flex align-items-center">
                                            
                                            <button type="button" class="btn btn-sm btn-secondary me-2 view-details-btn" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#proofDetailModal" 
                                                data-id="<?php echo $proof['proof_id']; ?>"
                                                data-shipment-id="<?php echo $proof['shipment_id']; ?>"
                                                data-tracking-number="<?php echo htmlspecialchars($proof['tracking_number']); ?>"
                                                data-method="<?php echo $method; ?>"
                                                data-amount="<?php echo htmlspecialchars(number_format($proof['amount'], 2)); ?>"
                                                data-status="<?php echo $proof_status; ?>"
                                                data-bank-path="<?php echo htmlspecialchars($proof['bank_proof_path'] ?? ''); ?>"
                                                data-crypto-curr="<?php echo htmlspecialchars($proof['crypto_currency'] ?? ''); ?>"
                                                data-crypto-raw="<?php echo htmlspecialchars($proof['crypto_amount_raw'] ?? ''); ?>"
                                                data-crypto-path="<?php echo htmlspecialchars($proof['crypto_proof_path'] ?? ''); ?>"
                                                data-gc-value="<?php echo htmlspecialchars(number_format($proof['giftcard_value_usd'] ?? 0, 2)); ?>"
                                                data-gc-front="<?php echo htmlspecialchars($proof['giftcard_proof_front_path'] ?? ''); ?>"
                                                data-gc-back="<?php echo htmlspecialchars($proof['giftcard_proof_back_path'] ?? ''); ?>"
                                                data-date="<?php echo date('M d, Y, g:i A', strtotime($proof['submission_date'])); ?>">
                                                <i class="fa-regular fa-eye"></i>
                                            </button>
                                            
                                            <?php if ($is_pending): ?>
                                            <a href="payment_proofs.php?action=approve&proof_id=<?php echo $proof['proof_id']; ?>&page=<?php echo $page; ?>" 
                                                class="btn btn-sm btn-success me-2" 
                                                onclick="return confirm('Are you sure you want to APPROVE this payment proof and mark Shipment #<?php echo $proof['shipment_id']; ?> as PAID?');"> 
                                                <i class="fa-regular fa-check"></i> Approve
                                            </a>
                                            
                                            <a href="payment_proofs.php?action=decline&proof_id=<?php echo $proof['proof_id']; ?>&page=<?php echo $page; ?>" 
                                                class="btn btn-sm btn-warning text-dark me-2" 
                                                onclick="return confirm('Are you sure you want to DECLINE this payment proof? The user will be able to submit a new proof.');"> 
                                                <i class="fa-regular fa-times"></i> Decline
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if (!$is_pending): ?>
                                            <a href="payment_proofs.php?delete_id=<?php echo $proof['proof_id']; ?>&page=<?php echo $page; ?>" 
                                                class="btn btn-sm btn-danger" 
                                                onclick="return confirm('Are you sure you want to DELETE this payment proof? This action cannot be undone.');"> 
                                                <i class="fa-regular fa-trash"></i>
                                            </a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                            <div class="alert alert-info shadow-sm mb-0">No payment proofs have been submitted yet.</div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($total_pages > 1): ?>
                    <div class="card-footer border-0 bg-white pt-0 pb-3">
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-end mb-0">

                                <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>">Previous</a>
                                </li>

                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                                <?php endfor; ?>

                                <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>">Next</a>
                                </li>

                            </ul>
                        </nav>
                    </div>
                    <?php endif; ?>
                </div>

            </div>
        </div>
    </div>
    <?php include "footer.php" ?>

<div class="modal fade" id="proofDetailModal" tabindex="-1" aria-labelledby="proofDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="proofDetailModalLabel">Payment Proof Details: ID <span id="modalProofId"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="proofDetailsContent">
                </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="modalDeclineBtn">Decline</button>
                <button type="button" class="btn btn-success" id="modalApproveBtn">Approve</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const detailModal = document.getElementById('proofDetailModal');
    const customColor = '#198754'; // Define the custom color

    // Helper function to create the file path input group
    function generateFileSection(label, path) {
        if (!path || path === 'null' || path === '') {
            return `
                <p class="fw-bold mb-1">${label}:</p>
                <div class="alert alert-danger small">No file provided.</div>
            `;
        }
        
        const displayPath = path.replace('uploads/payment_proofs/', '.../');
        const linkPath = `../${path}`; 

        return `
            <p class="fw-bold mb-1">${label}:</p>
            <div class="input-group mb-3">
                <input type="text" class="form-control form-control-sm" value="${displayPath}" readonly title="${path}">
                <a href="${linkPath}" target="_blank" class="btn btn-sm btn-outline-secondary">
                    <i class="bi bi-download"></i> View File
                </a>
            </div>
        `;
    }

    detailModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget; 
        
        // Retrieve all data from the button's data attributes (Payment Proof fields)
        const proofId = button.getAttribute('data-id');
        const shipmentId = button.getAttribute('data-shipment-id');
        const trackingNumber = button.getAttribute('data-tracking-number');
        const method = button.getAttribute('data-method');
        const amount = button.getAttribute('data-amount'); 
        const status = button.getAttribute('data-status'); // New: proof status
        const date = button.getAttribute('data-date');
        
        // Method-specific data
        const bankPath = button.getAttribute('data-bank-path');
        const cryptoCurr = button.getAttribute('data-crypto-curr');
        const cryptoRaw = button.getAttribute('data-crypto-raw');
        const cryptoPath = button.getAttribute('data-crypto-path');
        const gcValue = button.getAttribute('data-gc-value');
        const gcFront = button.getAttribute('data-gc-front');
        const gcBack = button.getAttribute('data-gc-back');

        // Update the modal header ID
        document.getElementById('modalProofId').textContent = proofId;

        let methodSpecificDetails = '';
        let proofFilesHtml = '';

        // Conditional rendering based on payment method
        switch (method) {
            case 'bank':
                methodSpecificDetails = `
                    <li class="list-group-item d-flex justify-content-between align-items-center bg-light">
                        Payment Proof Type: <span class="fw-bolder text-info fs-6">Bank Transfer</span>
                    </li>
                `;
                proofFilesHtml = generateFileSection('Bank Proof File', bankPath);
                break;

            case 'crypto':
                methodSpecificDetails = `
                    <li class="list-group-item d-flex justify-content-between align-items-center bg-light">
                        Payment Proof Type: <span class="fw-bolder text-warning fs-6">Cryptocurrency</span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        Crypto Currency: <span class="fw-bold text-uppercase">${cryptoCurr}</span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        Crypto Amount Sent: <span class="fw-bold">${cryptoRaw} ${cryptoCurr.toUpperCase()}</span>
                    </li>
                `;
                proofFilesHtml = generateFileSection('Crypto Transaction Proof', cryptoPath);
                break;

            case 'giftcard':
                methodSpecificDetails = `
                    <li class="list-group-item d-flex justify-content-between align-items-center bg-light">
                        Payment Proof Type: <span class="fw-bolder text-success fs-6">Gift Card</span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        Declared Card Value: <span class="fw-bold text-success">$${gcValue} USD</span>
                    </li>
                `;
                proofFilesHtml = 
                    generateFileSection('Gift Card Proof (Front)', gcFront) + 
                    generateFileSection('Gift Card Proof (Back)', gcBack);
                break;
            
            default:
                methodSpecificDetails = `
                    <li class="list-group-item d-flex justify-content-between align-items-center bg-light">
                        Proof Type: <span class="fw-bolder text-danger fs-6">Unknown Method</span>
                    </li>
                `;
                proofFilesHtml = '<div class="alert alert-danger">No proof file paths found for this method.</div>';
        }
        
        let statusBadge = '';
        if (status === 'Pending Review') {
            statusBadge = '<span class="badge bg-warning text-dark">Pending Review</span>';
        } else if (status === 'Approved') {
            statusBadge = '<span class="badge bg-success">Approved</span>';
        } else if (status === 'Declined') {
            statusBadge = '<span class="badge bg-danger">Declined</span>';
        } else {
            statusBadge = '<span class="badge bg-secondary">Unknown</span>';
        }
        
        // Construct the HTML content dynamically
        const detailsHtml = `
            <div class="row">
                <div class="col-lg-6">
                    <h5 class="mb-3" style="color: ${customColor};">Payment Summary</h5>
                    <ul class="list-group list-group-flush mb-4">
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            **Proof Status:** ${statusBadge}
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            **Tracking Number:** <a href="shipment_details.php?id=${shipmentId}" class="fw-bold text-decoration-none">${trackingNumber}</a>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            Submitted Amount (USD): <span class="fw-bold text-danger fs-5">$${amount}</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            Payment Method: <span class="fw-bold text-capitalize" style="color: ${customColor};">${method}</span>
                        </li>
                        ${methodSpecificDetails}
                        <li class="list-group-item d-flex justify-content-between align-items-center small text-muted">
                            Submission Date: <span>${date}</span>
                        </li>
                    </ul>
                </div>

                <div class="col-lg-6 border-start">
                    <h5 class="mb-3 text-primary">Uploaded Proofs</h5>
                    ${proofFilesHtml}
                    <div class="alert alert-info small mt-4" role="alert">
                        Important: The file link requires the 'uploads/payment_proofs/' directory to be in the parent folder (e.g., \`../uploads/...\`).
                    </div>
                </div>
            </div>
        `;

        document.getElementById('proofDetailsContent').innerHTML = detailsHtml;
        
        // --- Modal Action Button Logic ---
        const approveBtn = document.getElementById('modalApproveBtn');
        const declineBtn = document.getElementById('modalDeclineBtn');
        
        // Create the URL for the current page to redirect back to
        const redirectPage = `payment_proofs.php?page=<?php echo $page; ?>`;

        if (status === 'Pending Review') {
            // Show buttons and set URLs
            approveBtn.style.display = 'inline-block';
            declineBtn.style.display = 'inline-block';
            
            // Set hrefs dynamically
            approveBtn.onclick = function() {
                if (confirm(`Are you sure you want to APPROVE proof #${proofId} and mark shipment ${trackingNumber} as PAID?`)) {
                    window.location.href = `payment_proofs.php?action=approve&proof_id=${proofId}&page=<?php echo $page; ?>`;
                }
            };
            declineBtn.onclick = function() {
                if (confirm(`Are you sure you want to DECLINE proof #${proofId}? The user can then resubmit.`)) {
                    window.location.href = `payment_proofs.php?action=decline&proof_id=${proofId}&page=<?php echo $page; ?>`;
                }
            };
        } else {
            // Hide buttons if already approved or declined
            approveBtn.style.display = 'none';
            declineBtn.style.display = 'none';
        }
    });
});
</script>
</body>
</html>