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

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

$errors = [];
$success = '';

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$is_admin = $role_id == 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $expense_date = $_POST['expense_date'] ?? '';
    $store_id = intval($_POST['store_id'] ?? 0);
    $category_id = intval($_POST['category_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $reference = 'EXP-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid()), 0, 6));
    $status = $is_admin ? 'approved' : 'pending';

    if (!$expense_date) $errors[] = "Expense date is required.";
    if (!$store_id) $errors[] = "Store is required.";
    if (!$category_id) $errors[] = "Expense category is required.";
    if ($amount <= 0) $errors[] = "Enter a valid amount.";

    // Get account_id from expense category
    $catResult = $conn->query("SELECT account_id FROM expense_categories WHERE id = $category_id");
    $catRow = $catResult->fetch_assoc();
    $expense_account_id = $catRow['account_id'] ?? null;

    if (!$expense_account_id) $errors[] = "Selected expense category is not mapped to an account.";

    // Handle document upload
    $supporting_document = null;
    if (!empty($_FILES['supporting_document']) && $_FILES['supporting_document']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf', 'image/gif'];
        $fileType = $_FILES['supporting_document']['type'];
        if (!in_array($fileType, $allowedTypes)) {
            $errors[] = "Only JPG, PNG, GIF or PDF files allowed.";
        } else {
            $uploadDir = '../../uploads/expenses/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            $ext = pathinfo($_FILES['supporting_document']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('exp_') . '.' . $ext;
            $target = $uploadDir . $filename;
            if (move_uploaded_file($_FILES['supporting_document']['tmp_name'], $target)) {
                $supporting_document = $filename;
            } else {
                $errors[] = "Failed to upload file.";
            }
        }
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO expenses 
            (reference, store_id, expense_category_id, description, amount, expense_date, supporting_document, created_at, updated_at, added_by, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), ?, ?)");
        $stmt->bind_param("siisdssis", $reference, $store_id, $category_id, $description, $amount, $expense_date, $supporting_document, $user_id, $status);
        
        if ($stmt->execute()) {
            $success = "Expense recorded successfully. " . ($is_admin ? "Approved automatically." : "Awaiting approval.");
        } else {
            $errors[] = "Failed to save expense.";
        }
    }
}

// Fetch dropdowns
$stores = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name")->fetch_all(MYSQLI_ASSOC);
$categories = $conn->query("SELECT ec.id as category_id, ec.category_name, a.account_name 
                            FROM expense_categories ec 
                            LEFT JOIN accounts a ON ec.account_id = a.id 
                            ORDER BY ec.category_name")->fetch_all(MYSQLI_ASSOC);
?>

<!-- STYLE + FORM -->
<style>
body {
    background: url('../../images/profile.jpg') no-repeat center center fixed;
    background-size: cover;
    font-family: 'Segoe UI', sans-serif;
    color: #eee;
    margin: 0; padding: 0;
}
.form-container {
    max-width: 600px;
    margin: 100px auto;
    padding: 30px;
    border-radius: 15px;
    background: rgba(255, 255, 255, 0.1);
    box-shadow: 0 4px 30px rgba(0,0,0,0.1);
    border: 1px solid rgba(255,255,255,0.2);
    backdrop-filter: blur(10px);
}
h2 { color: #ffa500; text-align: center; margin-bottom: 25px; }
label { margin-top: 15px; font-weight: 500; display: block; }
input, select, textarea {
    width: 100%; padding: 10px; margin-top: 6px;
    border-radius: 8px; border: none;
    background: rgba(255,255,255,0.15); color: #fff;
}
textarea { resize: vertical; }
button {
    margin-top: 25px; padding: 12px; border-radius: 10px;
    background: rgba(255,165,0,0.85); color: #222;
    font-weight: bold; cursor: pointer; width: 100%;
}
button:hover { background: rgba(255,165,0,1); }
.error-message, .success-message {
    padding: 12px; border-radius: 8px; margin-bottom: 15px;
}
.error-message { background: rgba(248, 113, 113, 0.9); color: #fff; }
.success-message { background: rgba(34, 197, 94, 0.9); color: #fff; }
</style>

<div class="form-container">
    <h2>Record Expense</h2>

    <?php if ($errors): ?>
        <div class="error-message"><ul><?php foreach ($errors as $e) echo "<li>" . htmlspecialchars($e) . "</li>"; ?></ul></div>
    <?php elseif ($success): ?>
        <div class="success-message"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <label for="expense_date">Expense Date</label>
        <input type="date" name="expense_date" value="<?= htmlspecialchars($_POST['expense_date'] ?? date('Y-m-d')) ?>" required>

        <label for="store_id">Store</label>
        <select name="store_id" required>
            <option value="">-- Select Store --</option>
            <?php foreach ($stores as $s): ?>
                <option value="<?= $s['id'] ?>" <?= ($_POST['store_id'] ?? '') == $s['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label for="category_id">Expense Category</label>
        <select name="category_id" required>
            <option value="">-- Select Category --</option>
            <?php foreach ($categories as $cat): ?>
                <option value="<?= $cat['category_id'] ?>" <?= ($_POST['category_id'] ?? '') == $cat['category_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat['category_name'] . ' (' . $cat['account_name'] . ')') ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label for="amount">Amount</label>
        <input type="text" name="amount" value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>" required>

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

        <label for="supporting_document">Upload Supporting Document</label>
        <input type="file" name="supporting_document" accept=".jpg,.jpeg,.png,.pdf,.gif">

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

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