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

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

// Handle new bank transaction submission
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_transaction'])) {
    $transaction_date = $_POST['transaction_date'] ?? '';
    $reference = trim($_POST['reference'] ?? '');
    $amount = $_POST['amount'] ?? '';
    $type = $_POST['transaction_type'] ?? '';
    $description = trim($_POST['description'] ?? '');

    $valid_types = ['deposit', 'withdrawal', 'fee', 'interest', 'adjustment'];

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $transaction_date)) {
        $errors[] = "Please enter a valid transaction date.";
    }
    if ($reference === '') {
        $errors[] = "Reference cannot be empty.";
    }
    if (!is_numeric($amount)) {
        $errors[] = "Amount must be a valid number.";
    }
    if (!in_array($type, $valid_types)) {
        $errors[] = "Please select a valid transaction type.";
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO bank_transactions (transaction_date, reference, amount, type, description, reconciled, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, NOW(), NOW())");
        $stmt->bind_param("ssdss", $transaction_date, $reference, $amount, $type, $description);
        $stmt->execute();
        $stmt->close();

        header("Location: bank_transactions_entry.php?success=1");
        exit();
    }
}

// Fetch all recent transactions
$stmt = $conn->prepare("SELECT * FROM bank_transactions ORDER BY transaction_date DESC, id DESC LIMIT 50");
$stmt->execute();
$transactions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bank Transactions Entry</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            margin: 0;
            color: white;
        }
        .overlay {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .container {
            max-width: 1000px;
            margin: 50px auto;
            padding: 30px;
            border-radius: 15px;
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
        }
        h2 {
            text-align: center;
            color: #ffa500;
            margin-bottom: 20px;
        }
        form.add-transaction {
            background: rgba(255,255,255,0.12);
            padding: 20px;
            border-radius: 12px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            justify-content: center;
            margin-bottom: 30px;
        }
        form input, form select, form textarea, form button {
            padding: 10px;
            border-radius: 8px;
            border: none;
            background: rgba(255,255,255,0.15);
            color: white;
            min-width: 150px;
        }
        form button {
            background: #ffa500;
            color: black;
            font-weight: bold;
            cursor: pointer;
        }
        .success, .error {
            text-align: center;
            margin-bottom: 20px;
            padding: 12px;
            border-radius: 10px;
        }
        .success { background: rgba(0, 128, 0, 0.4); color: #0f0; }
        .error { background: rgba(255,0,0,0.4); color: #fff; }
        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(255,255,255,0.05);
            margin-top: 10px;
        }
        th, td {
            padding: 10px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            text-align: center;
        }
        th {
            background: rgba(0,0,0,0.4);
            color: #ffa500;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="container">

    <h2>🏦 Bank Transactions Entry</h2>

    <?php if (!empty($errors)): ?>
        <div class="error"><?= implode('<br>', array_map('htmlspecialchars', $errors)) ?></div>
    <?php elseif (isset($_GET['success'])): ?>
        <div class="success">Transaction added successfully!</div>
    <?php endif; ?>

    <form method="POST" class="add-transaction">
        <input type="date" name="transaction_date" required value="<?= htmlspecialchars($_POST['transaction_date'] ?? date('Y-m-d')) ?>">
        <input type="text" name="reference" placeholder="Reference" required value="<?= htmlspecialchars($_POST['reference'] ?? '') ?>">
        <input type="number" step="0.01" name="amount" placeholder="Amount" required value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>">
        <select name="transaction_type" required>
            <option value="">-- Transaction Type --</option>
            <?php
            $types = ['deposit'=>'Deposit', 'withdrawal'=>'Withdrawal', 'fee'=>'Bank Fee', 'interest'=>'Interest', 'adjustment'=>'Adjustment'];
            foreach ($types as $key => $label):
            ?>
            <option value="<?= $key ?>" <?= (($_POST['transaction_type'] ?? '') === $key) ? 'selected' : '' ?>><?= $label ?></option>
            <?php endforeach; ?>
        </select>
        <textarea name="description" placeholder="Description"><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
        <button type="submit" name="add_transaction">Add Transaction</button>
    </form>

    <h3 style="color: #ffa500; text-align:center;">Recent Transactions</h3>
    <table>
        <thead>
            <tr>
                <th>Date</th>
                <th>Reference</th>
                <th>Amount</th>
                <th>Type</th>
                <th>Description</th>
                <th>Reconciled</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($transactions)): ?>
                <tr><td colspan="6">No transactions yet.</td></tr>
            <?php else: ?>
                <?php foreach ($transactions as $tr): ?>
                    <tr>
                        <td><?= htmlspecialchars($tr['transaction_date']) ?></td>
                        <td><?= htmlspecialchars($tr['reference']) ?></td>
                        <td><?= number_format($tr['amount'],2) ?></td>
                        <td><?= ucfirst(htmlspecialchars($tr['type'])) ?></td>
                        <td><?= htmlspecialchars($tr['description']) ?></td>
                        <td><?= $tr['reconciled'] ? 'Yes' : 'No' ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

</div>
</body>
</html>
