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

// Restrict access to Managers (2) and Cashiers (3)
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [2, 3])) {
    header("Location: ../../index.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success = '';
$created_at = date('Y-m-d H:i:s');

// Fetch accounts
$accounts = [];
$result = $conn->query("SELECT id, account_code, account_name, account_type, bank_name, account_number FROM accounts ORDER BY account_name ASC");
while ($row = $result->fetch_assoc()) {
    $accounts[] = $row;
}
$result->free();

// Generate unique transaction reference
function generateTransactionReference() {
    return 'DEP-' . strtoupper(bin2hex(random_bytes(4))) . '-' . date('Ymd');
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $transaction_type = $_POST['transaction_type'] ?? '';
    $account_id = intval($_POST['account_id'] ?? 0);
    $transaction_date = $_POST['transaction_date'] ?? date('Y-m-d');
    $description = trim($_POST['description'] ?? '');
    $reference = generateTransactionReference();

    $deposit_slip = trim($_POST['deposit_slip'] ?? '');
    $cheque_number = trim($_POST['cheque_number'] ?? '');
    $mobile_transaction_id = trim($_POST['mobile_transaction_id'] ?? '');

    if ($amount <= 0) $errors[] = "Amount must be greater than zero.";
    if (!in_array($transaction_type, ['cash', 'cheque', 'mobile'])) $errors[] = "Invalid transaction type.";
    if ($account_id <= 0) $errors[] = "Please select a valid deposit account.";
    if (empty($description)) $errors[] = "Description is required.";

    $selected_account = array_filter($accounts, fn($a) => $a['id'] == $account_id);
    $selected_account = reset($selected_account);
    $bank_name = $selected_account['bank_name'] ?? '';
    $account_name = $selected_account['account_name'] ?? '';

    $upload_dir = '../../uploads/deposits/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
    $supporting_document = null;

    if (!empty($_FILES['supporting_document']['name'])) {
        $file = $_FILES['supporting_document'];
        $allowed_types = ['image/jpeg', 'image/png', 'application/pdf'];

        if (!in_array($file['type'], $allowed_types)) {
            $errors[] = "Unsupported file type.";
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Error uploading file.";
        } else {
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $new_filename = 'deposit_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $target_path = $upload_dir . $new_filename;
            if (!move_uploaded_file($file['tmp_name'], $target_path)) {
                $errors[] = "Failed to upload document.";
            } else {
                $supporting_document = $new_filename;
            }
        }
    }

    if (empty($errors)) {
        // Check for duplicate transaction
        $check = $conn->prepare("SELECT COUNT(*) FROM bank_transactions WHERE amount = ? AND account_id = ? AND transaction_date = ? AND type = 'deposit'");
        $check->bind_param("dis", $amount, $account_id, $transaction_date);
        $check->execute();
        $check->bind_result($exists);
        $check->fetch();
        $check->close();

        // Check for duplicate reference
        $ref_check = $conn->prepare("SELECT COUNT(*) FROM bank_transactions WHERE reference = ?");
        $ref_check->bind_param("s", $reference);
        $ref_check->execute();
        $ref_check->bind_result($ref_exists);
        $ref_check->fetch();
        $ref_check->close();

        if ($ref_exists > 0) $errors[] = "System generated duplicate reference. Please try again.";
        if ($exists > 0) $errors[] = "A deposit with the same amount, account, and date already exists.";

        if (empty($errors)) {
            $conn->begin_transaction();
            try {
                // Insert into bank_transactions
                $stmt = $conn->prepare("
                    INSERT INTO bank_transactions 
                    (transaction_date, reference, amount, type, description, supporting_document, account_id, deposit_slip, cheque_number, mobile_transaction_id, bank_name, reconciled, created_at, updated_at, status, created_by) 
                    VALUES (?, ?, ?, 'deposit', ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, 'pending', ?)
                ");
                $stmt->bind_param(
                    "ssdsiissssssi",
                    $transaction_date,
                    $reference,
                    $amount,
                    $description,
                    $supporting_document,
                    $account_id,
                    $deposit_slip,
                    $cheque_number,
                    $mobile_transaction_id,
                    $bank_name,
                    $created_at,
                    $created_at,
                    $user_id
                );
                $stmt->execute();
                $stmt->close();

                /* If sales-related account, insert into financial_transactions
                if (stripos($account_name, 'sales') !== false) {
                    $ft_stmt = $conn->prepare("
                        INSERT INTO financial_transactions 
                        (transaction_date, account_id, type, amount, payment_method, account, description, reference_id, store_id, created_by, status, created_at, updated_at, reconciliation_status) 
                        VALUES (?, ?, 'sale_payment', ?, ?, ?, ?, ?, 1, ?, 'pending', ?, ?, 'pending')
                    ");
                    $ft_stmt->bind_param(
                        "sidssssiss",
                        $transaction_date,
                        $account_id,
                        $amount,
                        $transaction_type,
                        $account_name,
                        $description,
                        $reference,
                        $user_id,
                        $created_at,
                        $created_at
                    );
                    $ft_stmt->execute();
                    $ft_stmt->close();
                }*/

                $conn->commit();
                $success = "Deposit recorded successfully. Reference: {$reference}";
                $_POST = [];
            } catch (Exception $e) {
                $conn->rollback();
                $errors[] = "Database error: " . $e->getMessage();
                if (!empty($supporting_document) && file_exists($target_path)) {
                    unlink($target_path);
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manual Deposit Entry</title>
<style>
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        color: #eee;
        margin: 0;
        padding: 0;
    }
    .glass-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(10px);
        padding: 30px;
        border-radius: 12px;
        max-width: 750px;
        margin: 40px auto;
        box-shadow: 0 8px 32px rgba(0,0,0,0.2);
    }
    label { font-weight: bold; margin-top: 12px; display: block; }
    input, select, textarea, button {
        width: 100%; padding: 10px; border-radius: 6px; border: none; margin-top: 6px;
    }
    .success { background: #44ff44; color: #111; padding: 10px; border-radius: 6px; margin-bottom: 10px; }
    .error { background: #ff4444; padding: 10px; border-radius: 6px; margin-bottom: 10px; }
    button { background: #ff6600; color: white; font-weight: bold; cursor: pointer; margin-top: 15px; }
    button:hover { background: #e65c00; }
</style>
<script>
function toggleDetails() {
    const type = document.getElementById('transaction_type').value;
    document.getElementById('cash_details').style.display = (type === 'cash') ? 'block' : 'none';
    document.getElementById('cheque_details').style.display = (type === 'cheque') ? 'block' : 'none';
    document.getElementById('mobile_details').style.display = (type === 'mobile') ? 'block' : 'none';
}

function showAccountDetails(select) {
    const selected = select.options[select.selectedIndex];
    const bank = selected.getAttribute('data-bank') || '';
    const number = selected.getAttribute('data-number') || '';
    const details = document.getElementById('account_extra_details');
    details.innerHTML = bank || number ? `<strong>Bank:</strong> ${bank}<br><strong>Account No:</strong> ${number}` : '';
}

document.addEventListener('DOMContentLoaded', function() {
    toggleDetails();
    showAccountDetails(document.querySelector('select[name="account_id"]'));
});
</script>
</head>
<body>

<div class="glass-card">
    <h2>Manual Deposit Entry</h2>

    <?php if ($success): ?>
        <div class="success"><?= htmlspecialchars($success) ?></div>
        <script>
            setTimeout(function() {
                document.querySelector('form').reset();
                document.getElementById('account_extra_details').innerHTML = '';
                toggleDetails();
            }, 100);
        </script>
    <?php endif; ?>

    <?php if (!empty($errors)): ?>
        <div class="error"><ul><?php foreach ($errors as $e) echo '<li>' . htmlspecialchars($e) . '</li>'; ?></ul></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <label>Amount (MWK)</label>
        <input type="number" step="0.01" name="amount" required value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>">

        <label>Transaction Type</label>
        <select name="transaction_type" id="transaction_type" onchange="toggleDetails()" required>
            <option value="">--Select Type--</option>
            <option value="cash" <?= ($_POST['transaction_type'] ?? '') == 'cash' ? 'selected' : '' ?>>Cash</option>
            <option value="cheque" <?= ($_POST['transaction_type'] ?? '') == 'cheque' ? 'selected' : '' ?>>Cheque</option>
            <option value="mobile" <?= ($_POST['transaction_type'] ?? '') == 'mobile' ? 'selected' : '' ?>>Mobile Money</option>
        </select>

        <div id="cash_details" style="display:none;">
            <label>Deposit Slip Number</label>
            <input type="text" name="deposit_slip" value="<?= htmlspecialchars($_POST['deposit_slip'] ?? '') ?>">
        </div>

        <div id="cheque_details" style="display:none;">
            <label>Cheque Number</label>
            <input type="text" name="cheque_number" value="<?= htmlspecialchars($_POST['cheque_number'] ?? '') ?>">
        </div>

        <div id="mobile_details" style="display:none;">
            <label>Mobile Transaction ID</label>
            <input type="text" name="mobile_transaction_id" value="<?= htmlspecialchars($_POST['mobile_transaction_id'] ?? '') ?>">
        </div>

        <label>Deposit Account</label>
        <select name="account_id" required onchange="showAccountDetails(this)">
            <option value="">-- Select Account --</option>
            <?php foreach ($accounts as $acc): ?>
                <option value="<?= $acc['id'] ?>"
                        data-bank="<?= htmlspecialchars($acc['bank_name']) ?>"
                        data-number="<?= htmlspecialchars($acc['account_number']) ?>"
                        <?= (($_POST['account_id'] ?? '') == $acc['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($acc['account_name'] . ' (' . $acc['account_code'] . ')') ?>
                </option>
            <?php endforeach; ?>
        </select>

        <div id="account_extra_details" style="margin-top:10px; font-size:0.9rem;"></div>

        <label>Description</label>
        <textarea name="description" rows="3" required><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>

        <label>Transaction Date</label>
        <input type="date" name="transaction_date" value="<?= htmlspecialchars($_POST['transaction_date'] ?? date('Y-m-d')) ?>" required>

        <label>Supporting Document (PDF, JPG, PNG)</label>
        <input type="file" name="supporting_document" accept=".jpg,.jpeg,.png,.pdf">

        <button type="submit">Submit Deposit</button>
    </form>
</div>

</body>
</html>
