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

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

// Filters
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$status_filter = $_GET['status'] ?? '-1';
$type_filter = $_GET['type'] ?? '';

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

if (in_array($status_filter, ['pending', 'reconciled', 'voided'])) {
    $where .= " AND reconciliation_status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

if (!empty($type_filter)) {
    $where .= " AND type = ?";
    $params[] = $type_filter;
    $types .= "s";
}

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

// Summaries
$total_deposits = $total_withdrawals = 0;
foreach ($transactions as $txn) {
    if ($txn['amount'] >= 0) {
        $total_deposits += $txn['amount'];
    } else {
        $total_withdrawals += abs($txn['amount']);
    }
}
$net_balance = $total_deposits - $total_withdrawals;
$total_transactions = count($transactions);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title><?= htmlspecialchars($page_title ?? 'Reconciliation Reports') ?></title>
<link rel="icon" type="image/png" href="../../images/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
    body {
        margin: 0;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        font-family: 'Segoe UI', sans-serif;
        color: #eee;
        min-height: 100vh;
    }
    .content {
        margin: 85px auto 0 auto; /* ← reserves space for fixed header */
        padding: 40px;
        max-width: 1850px;
        background: rgba(255,255,255,0.1);
        border-radius: 16px;
        backdrop-filter: blur(10px);
        box-shadow: 0 4px 15px rgba(255,165,0,0.3);
        border: 1px solid rgba(255,165,0,0.25);
    }
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    h1.page-title {
        color: #ffa500;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 700;
        font-size: 2rem;
    }
    h1.page-title img {
        height: 40px;
        width: auto;
    }
    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;
    }
    form.filters {
        margin-bottom: 30px;
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
        justify-content: center;
    }
    form.filters input,
    form.filters select,
    form.filters button {
        padding: 10px 15px;
        border-radius: 8px;
        border: none;
        font-weight: 600;
        background: rgba(255,255,255,0.15);
        color: #fff;
        min-width: 140px;
        text-align: center;
    }
    form.filters button {
        background: #ffa500;
        color: #222;
        cursor: pointer;
        min-width: auto;
        padding-left: 20px;
        padding-right: 20px;
    }
    .summary {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 30px;
        justify-content: center;
    }
    .summary > div {
        background: rgba(255,255,255,0.12);
        border-radius: 15px;
        padding: 15px 25px;
        color: #ffa500;
        font-weight: 700;
        min-width: 160px;
        text-align: center;
        box-shadow: 0 4px 15px rgba(255,165,0,0.25);
    }
    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
        background: rgba(255,255,255,0.05);
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(255,165,0,0.25);
    }
    thead tr {
        background: rgba(255,165,0,0.25);
        color: #fff;
    }
    th, td {
        padding: 12px 15px;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        text-align: center;
    }
    th {
        font-weight: 700;
    }
    tr:hover {
        background: rgba(255,165,0,0.15);
    }
</style>
</head>
<body>
<div class="content">
    <div class="page-header">
        <h1 class="page-title">
            <img src="../../images/logo.png" alt="Logo" />
            <?= htmlspecialchars($page_title ?? 'Reconciliation Reports') ?>
        </h1>
        <a href="reports_dashboard.php" class="back-link">&laquo; Back To Reports Dashoard</a>
    </div>

    <form class="filters" method="GET" novalidate>
        <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>" required>
        <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>" required>
        <select name="status">
            <option value="-1" <?= ($status_filter === '-1') ? 'selected' : '' ?>>All Statuses</option>
            <option value="pending" <?= ($status_filter === 'pending') ? 'selected' : '' ?>>Pending</option>
            <option value="reconciled" <?= ($status_filter === 'reconciled') ? 'selected' : '' ?>>Reconciled</option>
            <option value="voided" <?= ($status_filter === 'voided') ? 'selected' : '' ?>>Voided</option>
        </select>
        <select name="type">
            <option value="" <?= ($type_filter === '') ? 'selected' : '' ?>>All Types</option>
            <option value="deposit" <?= ($type_filter === 'deposit') ? 'selected' : '' ?>>Deposit</option>
            <option value="withdrawal" <?= ($type_filter === 'withdrawal') ? 'selected' : '' ?>>Withdrawal</option>
            <option value="Expense_payment" <?= ($type_filter === 'Expense_payment') ? 'selected' : '' ?>>Payment</option>
        </select>
        <button type="submit">Filter</button>
    </form>

    <div class="summary">
        <div>Total Deposits: <br> MWK <?= number_format($total_deposits, 2) ?></div>
        <div>Total Withdrawals: <br> MWK <?= number_format($total_withdrawals, 2) ?></div>
        <div>Net Balance: <br> MWK <?= number_format($net_balance, 2) ?></div>
        <div>Total Transactions: <br> <?= $total_transactions ?></div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Date</th>
                <th>Reference</th>
                <th>Amount (MWK)</th>
                <th>Type</th>
                <th>Status</th>
                <th>Reconciliation</th>
            </tr>
        </thead>
        <tbody>
        <?php if (empty($transactions)): ?>
            <tr><td colspan="6" style="color:#ffa500;">No transactions found.</td></tr>
        <?php else: ?>
            <?php foreach ($transactions as $txn): ?>
                <tr>
                    <td><?= htmlspecialchars(substr($txn['transaction_date'], 0, 10)) ?></td>
                    <td><?= htmlspecialchars($txn['reference']) ?></td>
                    <td><?= number_format($txn['amount'], 2) ?></td>
                    <td><?= ucfirst(htmlspecialchars($txn['type'])) ?></td>
                    <td><?= ucfirst(htmlspecialchars($txn['status'] ?? '')) ?></td>
                    <td><?= ucfirst(htmlspecialchars($txn['reconciliation_status'] ?? '')) ?></td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
</div>
</body>
</html>