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

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

// Fetch accounts for dropdown
$accounts_result = $conn->query("SELECT id, account_name, account_type FROM accounts ORDER BY account_name ASC");
$accounts = $accounts_result->fetch_all(MYSQLI_ASSOC);

// Filters
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$reconciled_filter = isset($_GET['reconciled']) ? intval($_GET['reconciled']) : -1;

$where = "WHERE DATE(transaction_date) BETWEEN ? AND ?";
$params = [$date_from, $date_to];
$types = "ss";

if ($reconciled_filter === 0) {
    $where .= " AND reconciled = 0";
} elseif ($reconciled_filter === 1) {
    $where .= " AND reconciled = 1";
}

$stmt = $conn->prepare("SELECT * FROM bank_transactions $where ORDER BY transaction_date DESC");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$bank_txns = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_deposits = $total_withdrawals = 0;
foreach ($bank_txns as $txn) {
    if ($txn['amount'] >= 0) {
        $total_deposits += $txn['amount'];
    } else {
        $total_withdrawals += abs($txn['amount']);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Bank Reconciliation</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<style>
    /* Background and font */
    body, html {
        margin: 0; padding: 0;
        min-height: 100vh;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        color: #eee;
        overflow-x: hidden;
    }
    /* Glassmorphic container */
    .container {
        max-width: 1850px;
        margin: 40px auto;
        padding: 30px 40px;
        background: rgba(255,255,255,0.1);
        box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 20px;
        border: 1px solid rgba(255,255,255,0.18);
        min-height: 80vh;
    }
    h2 {
        text-align: center;
        color: #ffa500;
        margin-bottom: 25px;
        font-weight: 700;
        font-size: 2.4rem;
        user-select: none;
    }
    .btn-back {
        display: inline-block;
        background: #ffa500;
        color: #222;
        padding: 10px 18px;
        border-radius: 12px;
        font-weight: 700;
        text-decoration: none;
        transition: background 0.3s ease;
        margin-bottom: 20px;
        user-select: none;
    }
    .btn-back:hover {
        background: #cc8400;
    }
    form.filters {
        display: flex;
        gap: 16px;
        justify-content: center;
        margin-bottom: 30px;
        flex-wrap: wrap;
    }
    form.filters input[type="date"],
    form.filters select,
    form.filters button {
        padding: 12px 18px;
        border-radius: 12px;
        border: none;
        font-size: 1rem;
        outline: none;
        min-width: 150px;
        transition: box-shadow 0.25s ease;
        user-select: none;
    }
    form.filters input[type="date"]:focus,
    form.filters select:focus,
    form.filters button:hover {
        box-shadow: 0 0 8px #ffa500;
        cursor: pointer;
    }
    form.filters button {
        background: #ffa500;
        color: #222;
        font-weight: 700;
        min-width: 110px;
        user-select: none;
    }
    .summary {
        display: flex;
        gap: 25px;
        justify-content: center;
        flex-wrap: wrap;
        margin-bottom: 35px;
    }
    .summary div {
        background: rgba(255,255,255,0.12);
        padding: 14px 22px;
        border-radius: 16px;
        color: #ffa500;
        font-weight: 600;
        font-size: 1.1rem;
        user-select: none;
        min-width: 180px;
        text-align: center;
        box-shadow: 0 0 12px rgba(255, 165, 0, 0.3);
    }
    table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(255,255,255,0.06);
        font-size: 14px;
        user-select: text;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 0 20px rgba(0,0,0,0.2);
    }
    thead tr {
        background: rgba(0,0,0,0.5);
        color: #ffa500;
        user-select: none;
    }
    th, td {
        padding: 12px 10px;
        border-bottom: 1px solid rgba(255,255,255,0.12);
        text-align: center;
        vertical-align: middle;
    }
    tbody tr:hover {
        background: rgba(255,165,0,0.12);
    }
    .btn-action {
        padding: 8px 16px;
        border-radius: 12px;
        border: none;
        cursor: pointer;
        font-weight: 700;
        user-select: none;
        background: #ffa500;
        color: #222;
        transition: background 0.3s ease;
    }
    .btn-action:hover {
        background: #cc8400;
    }
    select.account-select {
        padding: 8px 12px;
        border-radius: 12px;
        border: none;
        font-weight: 600;
        background: rgba(255,255,255,0.1);
        color: #eee;
        user-select: none;
        min-width: 170px;
        transition: box-shadow 0.25s ease;
    }
    select.account-select:focus {
        box-shadow: 0 0 10px #ffa500;
        outline: none;
    }
    .autocomplete-link {
        width: 160px !important;
        padding: 8px 12px !important;
        border-radius: 12px !important;
        border: none !important;
        font-weight: 600 !important;
        font-size: 13px !important;
        color: #222 !important;
        user-select: text !important;
    }
    .link-preview {
        margin-top: 6px;
        font-size: 12px;
        color: #ffa500;
        min-height: 18px;
        user-select: none;
    }
    /* Responsive tweaks */
    @media (max-width: 800px) {
        form.filters {
            flex-direction: column;
            align-items: center;
        }
        .summary {
            flex-direction: column;
            gap: 12px;
        }
        table {
            font-size: 12px;
        }
        select.account-select, .autocomplete-link {
            width: 100% !important;
            min-width: unset !important;
        }
    }
</style>
</head>
<body>

<div class="container">
    <a href="../../accountant/accountant_dashboard.php" class="btn-back">&larr; Back</a>
    <h2>🏦 Bank Reconciliation</h2>

    <form class="filters" method="GET" autocomplete="off">
        <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>" required />
        <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>" required />
        <select name="reconciled" aria-label="Filter by reconciliation status">
            <option value="-1" <?= $reconciled_filter === -1 ? 'selected' : '' ?>>All</option>
            <option value="1" <?= $reconciled_filter === 1 ? 'selected' : '' ?>>Reconciled</option>
            <option value="0" <?= $reconciled_filter === 0 ? 'selected' : '' ?>>Unreconciled</option>
        </select>
        <button type="submit" aria-label="Filter bank transactions">Filter</button>
    </form>

    <div class="summary" aria-live="polite" aria-atomic="true">
        <div><strong>Total Deposits:</strong><br>MWK <?= number_format($total_deposits, 2) ?></div>
        <div><strong>Total Withdrawals:</strong><br>MWK <?= number_format($total_withdrawals, 2) ?></div>
        <div><strong>Net Balance:</strong><br>MWK <?= number_format($total_deposits - $total_withdrawals, 2) ?></div>
        <div><strong>Total Transactions:</strong><br><?= count($bank_txns) ?></div>
    </div>

    <table aria-describedby="bankReconciliationTableDesc" role="grid" tabindex="0">
        <caption id="bankReconciliationTableDesc" class="sr-only">List of bank transactions available for reconciliation</caption>
        <thead>
            <tr>
                <th scope="col">Date</th>
                <th scope="col">Reference</th>
                <th scope="col">Description</th>
                <th scope="col">Amount</th>
                <th scope="col">Type</th>
                <th scope="col">Status</th>
                <th scope="col">Account</th>
                <th scope="col">Action</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($bank_txns as $txn): ?>
            <tr data-txn-id="<?= (int)$txn['id'] ?>">
                <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($txn['type']) ?></td>
                <td>
                    <?php if ($txn['reconciled']): ?>
                        <span style="color:#28a745; user-select:none;">✔️ Approved</span>
                    <?php else: ?>
                        <span style="color:#ffc107; user-select:none;">⏳ Pending</span>
                    <?php endif; ?>
                </td>
                <td>
                    <select class="account-select" required aria-label="Select account for transaction <?= htmlspecialchars($txn['reference']) ?>">
                        <option value="">Select Account</option>
                        <?php foreach ($accounts as $acc): ?>
                            <option value="<?= $acc['id'] ?>" <?= $acc['id'] == $txn['account_id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($acc['account_name']) ?> (<?= $acc['account_type'] ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </td>
                <td>
                    <form class="reconcile-form" aria-label="Reconciliation form for transaction <?= htmlspecialchars($txn['reference']) ?>">
                        <input type="hidden" name="txn_id" value="<?= (int)$txn['id'] ?>" />
                        <input type="text" class="autocomplete-link" placeholder="Ref/ID Search" autocomplete="off" aria-describedby="linkHelp_<?= (int)$txn['id'] ?>" />
                        <div class="link-preview" id="linkHelp_<?= (int)$txn['id'] ?>"></div>
                        <button type="submit" class="btn-action" aria-live="polite"><?= $txn['reconciled'] ? '✖️ Unreconcile' : '✔️ Reconcile' ?></button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<script>
$(function() {
    const sources = {
        sale: 'autocomplete_sales.php',
        expense: 'autocomplete_expenses.php',
        payment: 'autocomplete_payments.php'
    };

    const previews = {
        sale: 'preview_sale.php?id=',
        expense: 'preview_expense.php?id=',
        payment: 'preview_payment.php?id='
    };

    $('.autocomplete-link').autocomplete({
        source: function(request, response) {
            let results = [];
            let pending = 3;
            for (let type in sources) {
                $.getJSON(sources[type], { term: request.term }, function(data) {
                    data.forEach(item => {
                        results.push({ 
                            label: `${type.toUpperCase()} #${item.id} - MWK ${parseFloat(item.amount || item.total_amount).toFixed(2)}`, 
                            value: `${type}:${item.id}` 
                        });
                    });
                }).always(function() {
                    pending--;
                    if (pending === 0) response(results);
                });
            }
        },
        minLength: 1,
        select: function(e, ui) {
            const [type, id] = ui.item.value.split(':');
            const previewDiv = $(this).siblings('.link-preview');
            $.getJSON(previews[type] + id, function(data) {
                if (data.success) {
                    previewDiv.html(`<a href="../accountant/view_${type}.php?id=${id}" target="_blank">${ui.item.label}</a>`);
                    $(e.target).data('valid', true);
                    $(e.target).data('type', type);
                    $(e.target).data('id', id);
                } else {
                    previewDiv.html('<span style="color:red;">Invalid</span>');
                    $(e.target).data('valid', false);
                }
            });
        }
    });

    $('.reconcile-form').on('submit', function(e) {
        e.preventDefault();
        const form = $(this);
        const input = form.find('.autocomplete-link');
        const isValid = input.data('valid');
        const txn_id = form.find('input[name="txn_id"]').val();
        const action = form.find('button').text().includes('Unreconcile') ? 'unreconcile' : 'reconcile';
        const type = input.data('type');
        const id = input.data('id');
        const account_id = form.closest('tr').find('.account-select').val();

        if (!account_id) {
            alert('Please select an account.');
            return;
        }

        if (action === 'reconcile' && (!isValid || !id || !type)) {
            alert('Invalid transaction match. Please select a valid Sale, Expense, or Payment.');
            return;
        }

        const payload = {
            txn_id: txn_id,
            action: action,
            link_type: type || null,
            link_id: id || null,
            account_id: account_id
        };

        if (!confirm('Are you sure you want to proceed?')) return;

        fetch('bank_reconciliation_action.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        }).then(res => res.json())
        .then(data => {
            if (data.success) location.reload();
            else alert(data.message || 'Error processing reconciliation.');
        }).catch(() => alert('Failed to process. Please try again.'));
    });
});
</script>

</body>
</html>
