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

// Allow only managers (role_id 2) or cashiers (role_id 3) to access this page
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [2,3])) {
    header("Location: ../../index.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $reference = trim($_POST['reference'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $transaction_date = $_POST['transaction_date'] ?? date('Y-m-d');
    $created_at = date('Y-m-d H:i:s');

    // Validate
    if ($amount <= 0) {
        $errors[] = "Amount must be greater than zero.";
    }
    if (empty($reference)) {
        $errors[] = "Reference is required.";
    }
    if (empty($description)) {
        $errors[] = "Description is required.";
    }

    // Handle file upload
    $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. Allowed: JPG, PNG, PDF.";
        } elseif ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Error uploading file.";
        } else {
            // Generate unique filename
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $new_filename = 'deposit_' . time() . '_' . bin2hex(random_bytes(5)) . '.' . $ext;
            $target_path = $upload_dir . $new_filename;

            if (!move_uploaded_file($file['tmp_name'], $target_path)) {
                $errors[] = "Failed to move uploaded file.";
            } else {
                $supporting_document = $new_filename;
            }
        }
    }

    if (empty($errors)) {
        // Insert deposit into bank_transactions with status 'pending' and type 'deposit'
        $stmt = $conn->prepare("INSERT INTO bank_transactions 
            (transaction_date, reference, amount, type, description, reconciled, created_at, updated_at, status, supporting_document)
            VALUES (?, ?, ?, 'deposit', ?, 0, ?, ?, 'pending', ?)");
        $stmt->bind_param("ssdssss", $transaction_date, $reference, $amount, $description, $created_at, $created_at, $supporting_document);
        if ($stmt->execute()) {
            $success = "Deposit recorded successfully and is pending approval.";
        } else {
            $errors[] = "Database error: " . $stmt->error;
            if ($supporting_document) {
                unlink($target_path); // Delete uploaded file if DB fails
            }
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Manual Deposit Entry</title>
    <link href="../../css/styles.css" rel="stylesheet" />
    <style>
        /* Basic styling, adjust to your glassmorphism design */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #121212;
            color: #eee;
            padding: 20px;
        }
        .glass-card {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            padding: 30px;
            max-width: 500px;
            margin: 0 auto;
            box-shadow: 0 8px 32px 0 rgba(255,255,255,0.2);
            backdrop-filter: blur(10px);
        }
        input, textarea, button {
            width: 100%;
            margin-top: 10px;
            padding: 10px;
            border-radius: 6px;
            border: none;
            font-size: 1rem;
        }
        input[type="file"] {
            padding: 3px;
        }
        button {
            background: #ff6600;
            color: white;
            font-weight: bold;
            cursor: pointer;
            margin-top: 20px;
        }
        button:hover {
            background: #e65c00;
        }
        .error {
            background: #ff4444;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 6px;
        }
        .success {
            background: #44ff44;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 6px;
            color: #111;
        }
    </style>
</head>
<body>
    <div class="glass-card">
        <h2>Manual Deposit Entry</h2>

        <?php if ($errors): ?>
            <div class="error">
                <ul>
                    <?php foreach ($errors as $err): ?>
                        <li><?= htmlspecialchars($err) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

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

            <label for="reference">Reference</label>
            <input type="text" name="reference" id="reference" required maxlength="255" value="<?= htmlspecialchars($_POST['reference'] ?? '') ?>" />

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

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

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

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