<?php
session_start();
include('../../includes/config.php');
include('../../includes/header.php');

if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 4])) {
    die("Access denied.");
}

$success = isset($_GET['success']) && $_GET['success'] == 1 ? "Reconciliation completed successfully." : "";

// Unreconciled deposits
$deposits = $conn->query("
    SELECT bt.id, bt.reference, bt.amount, bt.transaction_date, a.account_name 
    FROM bank_transactions bt
    JOIN accounts a ON bt.account_id = a.id
    WHERE bt.type = 'deposit' AND bt.reconciliation_status = 'pending' AND bt.status = 'approved'
");

// Unmatched financial transactions
$fts = $conn->query("
    SELECT ft.id, ft.amount, ft.description, ft.transaction_date, a.account_name
    FROM financial_transactions ft
    JOIN accounts a ON ft.account_id = a.id
    WHERE ft.type = 'sale_income' AND ft.reconciliation_status = 'pending'
    ORDER BY ft.transaction_date DESC
");

// Previously reconciled
$reconciled = $conn->query("
    SELECT l.id as link_id, bt.reference as deposit_ref, ft.description, ft.amount, ft.id as ft_id
    FROM deposit_reconciliation_links l
    JOIN bank_transactions bt ON l.bank_transaction_id = bt.id
    JOIN financial_transactions ft ON l.financial_transaction_id = ft.id
    ORDER BY l.created_at DESC
");
?>

<style>
body {
    font-family: 'Segoe UI', sans-serif;
    background: url('../../images/profile.jpg') no-repeat center center fixed;
    background-size: cover;
    margin: 0;
    color: #eee;
}
.container {
    max-width: 1850px;
    margin: 60px auto;
    padding: 20px 40px;
    background: rgba(255, 255, 255, 0.07);
    backdrop-filter: blur(14px);
    border-radius: 18px;
    box-shadow: 0 0 18px rgba(255, 165, 0, 0.3);
}
h2, h3 {
    color: #ffa500;
    margin-top: 20px;
}
label {
    display: block;
    margin-top: 20px;
    font-weight: bold;
}
select, input[type="number"] {
    padding: 8px 12px;
    border-radius: 8px;
    border: 1px solid rgba(255,255,255,0.15);
    background: rgba(255,255,255,0.1);
    color: #fff;
    margin-top: 5px;
    width: 100%;
    max-width: 400px;
}
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}
th, td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid rgba(255,255,255,0.1);
}
th {
    background: rgba(255,165,0,0.25);
    color: #fff;
}
tr:hover {
    background: rgba(255,255,255,0.08);
}
.total-info {
    margin-top: 20px;
}
.total-info span {
    font-weight: bold;
    color: #ffa500;
}
button {
    margin-top: 20px;
    margin-right: 10px;
    padding: 10px 20px;
    background: #ffa500;
    color: #222;
    border: none;
    border-radius: 10px;
    font-weight: bold;
    cursor: pointer;
}
button:disabled {
    background: gray;
    cursor: not-allowed;
}
.success-msg {
    background: rgba(0,255,0,0.12);
    border-left: 5px solid limegreen;
    padding: 10px 16px;
    margin: 20px 0;
    font-weight: bold;
    color: #0f0;
    border-radius: 8px;
}
a {
    color: #ffa500;
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
}
.rollback-btn {
    padding: 6px 10px;
    background: crimson;
    color: #fff;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}
a.back-link {
        color: #ffa500;
        text-decoration: none;
        font-weight: 600;
        border: 1.5px solid #ffa500;
        padding: 6px 14px;
        border-radius: 8px;
        transition: background-color 0.3s ease, color 0.3s ease;
        white-space: nowrap;
    }
    a.back-link:hover {
        background-color: #ffa500;
        color: #222;
    }
</style>

<div class="container">
       <a href="reports_dashboard.php" class="back-link">&laquo; Back To Reports Dashoard</a>

    <h2>🧾 Deposit Reconciliation</h2>
    <?php if ($success): ?>
        <div class="success-msg"><?= $success ?></div>
    <?php endif; ?>

    <form method="POST" action="reconcile_deposit_backend.php" onsubmit="return validateSubmission()">
        <label for="deposit_id">Select Deposit</label>
        <select name="deposit_id" id="deposit_id" required onchange="resetSelection()">
            <option value="">-- Select a Deposit --</option>
            <?php while ($d = $deposits->fetch_assoc()): ?>
                <option value="<?= $d['id'] ?>" data-amount="<?= $d['amount'] ?>">
                    <?= htmlspecialchars($d['reference']) ?> (<?= htmlspecialchars($d['account_name']) ?> - <?= number_format($d['amount'],2) ?>)
                </option>
            <?php endwhile; ?>
        </select>

        <h3>🔗 Match to Financial Transactions</h3>
        <table id="ft_table">
            <thead>
                <tr>
                    <th>Select</th>
                    <th>Date</th>
                    <th>Description</th>
                    <th>Account</th>
                    <th style="text-align:right;">FT Amount</th>
                    <th style="text-align:right;">Reconcile Amount</th>
                </tr>
            </thead>
            <tbody>
            <?php while ($f = $fts->fetch_assoc()): ?>
                <tr>
                    <td><input type="checkbox" name="fts[<?= $f['id'] ?>][select]" onchange="updateTotal()"></td>
                    <td><?= $f['transaction_date'] ?></td>
                    <td><a href="#" onclick="showModal('<?= htmlspecialchars($f['description']) ?>')"><?= htmlspecialchars($f['description']) ?></a></td>
                    <td><?= htmlspecialchars($f['account_name']) ?></td>
                    <td style="text-align:right;"><?= number_format($f['amount'], 2) ?></td>
                    <td style="text-align:right;">
                        <input type="number" name="fts[<?= $f['id'] ?>][amount]" step="0.01" placeholder="0.00" disabled>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>

        <div class="total-info">
            <p>Total Reconciled: MWK <span id="total_display">0.00</span></p>
            <p>Deposit Amount: MWK <span id="deposit_display">0.00</span></p>
        </div>

        <button type="submit" id="submit_btn" disabled>✅ Finalize Reconciliation</button>
        <button type="button" onclick="exportTable('excel')">📊 Export to Excel</button>
        <button type="button" onclick="exportTable('pdf')">🧾 Export to PDF</button>
    </form>

    <h3>🕘 Reconciled Transactions (Rollback)</h3>
    <table>
        <thead>
            <tr>
                <th>Deposit Ref</th>
                <th>FT Description</th>
                <th style="text-align:right;">Amount</th>
                <th style="text-align:center;">Action</th>
            </tr>
        </thead>
        <tbody>
        <?php while ($r = $reconciled->fetch_assoc()): ?>
            <tr id="rollback_row_<?= $r['link_id'] ?>">
                <td><?= $r['deposit_ref'] ?></td>
                <td><?= $r['description'] ?></td>
                <td style="text-align:right;"><?= number_format($r['amount'], 2) ?></td>
                <td style="text-align:center;">
                    <button class="rollback-btn" onclick="rollbackLink(<?= $r['link_id'] ?>)">↩ Undo</button>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- Modal -->
<div id="modal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:#000a;z-index:1000;">
    <div style="background:#fff;color:#000;padding:30px;margin:100px auto;width:400px;border-radius:12px;text-align:center;">
        <h3>Transaction Details</h3>
        <p id="modalContent"></p>
        <button onclick="document.getElementById('modal').style.display='none'">Close</button>
    </div>
</div>

<script>
function validateSubmission() {
    return confirm("Are you sure you want to finalize reconciliation?");
}

function resetSelection() {
    const depositSelect = document.getElementById('deposit_id');
    if (depositSelect.selectedIndex === 0) {
        document.getElementById('deposit_display').textContent = '0.00';
        document.getElementById('total_display').textContent = '0.00';
        document.getElementById('submit_btn').disabled = true;
        document.querySelectorAll('#ft_table tbody tr').forEach(row => {
            const cb = row.querySelector('input[type="checkbox"]');
            cb.checked = false;
            const input = row.querySelector('input[type="number"]');
            input.disabled = true;
            input.value = '';
        });
        return;
    }
    const amount = parseFloat(depositSelect.selectedOptions[0].dataset.amount || 0);
    document.getElementById('deposit_display').textContent = amount.toFixed(2);
    document.getElementById('total_display').textContent = '0.00';
    document.getElementById('submit_btn').disabled = true;

    document.querySelectorAll('#ft_table tbody tr').forEach(row => {
        const cb = row.querySelector('input[type="checkbox"]');
        cb.checked = false;
        const input = row.querySelector('input[type="number"]');
        input.disabled = true;
        input.value = '';
    });
}

function updateTotal() {
    const depositSelect = document.getElementById('deposit_id');
    if (depositSelect.selectedIndex === 0) return;

    const depositAmount = parseFloat(depositSelect.selectedOptions[0].dataset.amount);
    let total = 0;

    document.querySelectorAll('#ft_table tbody tr').forEach(row => {
        const checkbox = row.querySelector('input[type="checkbox"]');
        const input = row.querySelector('input[type="number"]');
        if (checkbox.checked) {
            input.disabled = false;

            // Remove commas/spaces and parse float
            let rawVal = (input.value || '').replace(/[, ]+/g, '');
            let val = parseFloat(rawVal);
            if (isNaN(val)) val = 0;
            total += val;
        } else {
            input.disabled = true;
            input.value = '';
        }
    });

    document.getElementById('total_display').textContent = total.toFixed(2);

    // Enable submit only if total matches depositAmount within 0.01 tolerance
    document.getElementById('submit_btn').disabled = Math.abs(total - depositAmount) > 0.01;
}

// Set input to FT amount on checkbox check, clear on uncheck, update total
document.querySelectorAll('#ft_table tbody input[type="checkbox"]').forEach(cb => {
    cb.addEventListener('change', () => {
        const tr = cb.closest('tr');
        const input = tr.querySelector('input[type="number"]');
        const ftAmountText = tr.querySelector('td:nth-child(5)').textContent || '0';
        const ftAmount = parseFloat(ftAmountText.replace(/,/g, '')) || 0;

        if (cb.checked) {
            input.disabled = false;
            input.value = ftAmount.toFixed(2);
        } else {
            input.disabled = true;
            input.value = '';
        }
        updateTotal();
    });
});

// Update total live when user types in the amount inputs
document.querySelectorAll('#ft_table tbody input[type="number"]').forEach(input => {
    input.addEventListener('input', updateTotal);
});
    document.getElementById('total_display').innerText = total.toFixed(2);
    document.getElementById('submit_btn').disabled = Math.abs(total - depositAmount) > 0.01;


function rollbackLink(link_id) {
    if (!confirm("Are you sure you want to undo this reconciliation?")) return;

    fetch('rollback_reconciliation.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'link_ids=' + encodeURIComponent(link_id)
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            data.rolled_back.forEach(id => {
                const row = document.getElementById('rollback_row_' + id);
                if (row) row.remove();
            });
            alert("Rollback successful.");
        } else {
            alert("Rollback failed: " + data.message);
        }
    });
}

function showModal(content) {
    document.getElementById('modalContent').innerText = content;
    document.getElementById('modal').style.display = 'block';
}

function exportTable(type) {
    const table = document.getElementById('ft_table');
    if (type === 'excel') {
        const data = table.outerHTML.replace(/ /g, '%20');
        const a = document.createElement('a');
        a.href = 'data:application/vnd.ms-excel,' + data;
        a.download = 'reconciliation.xls';
        a.click();
    } else if (type === 'pdf') {
        window.print();
    }
}
</script>

<?php include('../../includes/footer.php'); ?>
