<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) { // Accountant only
    header("Location: ../../index.php");
    exit;
}

include('../../includes/config.php');

// Fetch all pending transactions needing approval with created_by info
$stmt = $conn->prepare("
    SELECT bt.*, u.first_name, u.last_name 
    FROM bank_transactions bt 
    LEFT JOIN users u ON bt.created_by = u.id 
    WHERE bt.status = 'pending' 
    ORDER BY bt.transaction_date DESC
");
$stmt->execute();
$pending_transactions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Bank Transaction Approvals</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        margin: 0;
        color: #eee;
        min-height: 100vh;
    }
    .overlay {
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.65);
        z-index: -1;
    }
    .container {
        max-width: 1850px;
        margin: 60px auto;
        background: rgba(255, 255, 255, 0.1);
        padding: 30px 40px;
        border-radius: 20px;
        backdrop-filter: blur(12px);
        box-shadow: 0 10px 30px rgba(255, 165, 0, 0.3);
        border: 1px solid rgba(255, 165, 0, 0.25);
    }
    h2 {
        text-align: center;
        color: #ffa500;
        margin-bottom: 25px;
        font-weight: 700;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(255,255,255,0.05);
        border-radius: 15px;
        overflow: hidden;
        font-size: 14px;
        user-select: none;
    }
    th, td {
        padding: 14px 16px;
        text-align: center;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        color: #eee;
        vertical-align: middle;
    }
    th {
        background: rgba(0,0,0,0.5);
        color: #ffa500;
        font-weight: 700;
    }
    tr:hover {
        background: rgba(255, 165, 0, 0.15);
    }
    .btn-approve, .btn-void {
        padding: 8px 18px;
        border-radius: 12px;
        border: none;
        cursor: pointer;
        font-weight: 700;
        color: #222;
        transition: background-color 0.25s ease;
        min-width: 110px;
        user-select: none;
    }
    .btn-approve {
        background: #28a745;
    }
    .btn-approve:hover:not(:disabled) {
        background: #218838;
        color: #fff;
    }
    .btn-void {
        background: #dc3545;
    }
    .btn-void:hover:not(:disabled) {
        background: #b02a37;
        color: #fff;
    }
    button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<body>
<div class="overlay"></div>
<div class="container">
    <a href="../../accountant/accountant_dashboard.php" style="color:#ffa500; font-weight:700; display:inline-block; margin-bottom:20px;">&larr; Back to Dashboard</a>
    <h2>Pending Bank Transaction Approvals</h2>

    <?php if(empty($pending_transactions)): ?>
        <p style="text-align:center; color:#ffa500; font-weight:700;">No transactions need approval right now.</p>
    <?php else: ?>
    <table role="grid" aria-label="Pending bank transactions needing approval">
        <thead>
            <tr>
                <th scope="col">Date</th>
                <th scope="col">Reference</th>
                <th scope="col">Description</th>
                <th scope="col">Amount (MWK)</th>
                <th scope="col">Type</th>
                <th scope="col">Created By</th>
                <th scope="col" style="min-width: 230px;">Action</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($pending_transactions as $txn): ?>
            <tr>
                <td><?= htmlspecialchars(substr($txn['transaction_date'], 0, 10)) ?></td>
                <td><?= htmlspecialchars($txn['reference']) ?></td>
                <td><?= htmlspecialchars($txn['description']) ?></td>
                <td><?= number_format($txn['amount'], 2) ?></td>
                <td><?= ucfirst(htmlspecialchars($txn['type'])) ?></td>
                <td>
                    <?= htmlspecialchars(trim($txn['first_name'] . ' ' . $txn['last_name'])) ?: '<em>Unknown</em>' ?>
                </td>
                <td>
                    <button class="btn-approve" data-id="<?= (int)$txn['id'] ?>" aria-label="Approve transaction <?= htmlspecialchars($txn['reference']) ?>">✔️ Approve</button>
                    <button class="btn-void" data-id="<?= (int)$txn['id'] ?>" aria-label="Void transaction <?= htmlspecialchars($txn['reference']) ?>">❌ Void</button>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>

<script>
$(function(){
    function handleAction(txnId, action) {
        if (!confirm(`Are you sure you want to ${action} transaction ID ${txnId}?`)) return;

        const approveBtn = $(`.btn-approve[data-id=${txnId}]`);
        const voidBtn = $(`.btn-void[data-id=${txnId}]`);
        approveBtn.prop('disabled', true);
        voidBtn.prop('disabled', true);

        $.ajax({
            url: 'bank_transaction_approval_action.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ txn_id: txnId, action: action }),
            success: function(response){
                if(response.success){
                    alert(response.message);
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                    approveBtn.prop('disabled', false);
                    voidBtn.prop('disabled', false);
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert(`Request failed: ${textStatus}, ${errorThrown}\n${jqXHR.responseText}`);
                approveBtn.prop('disabled', false);
                voidBtn.prop('disabled', false);
            }
        });
    }

    $('.btn-approve').click(function(){
        const txnId = $(this).data('id');
        handleAction(txnId, 'approved');
    });

    $('.btn-void').click(function(){
        const txnId = $(this).data('id');
        handleAction(txnId, 'voided');
    });
});
</script>
</body>
</html>
