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

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

$errors = [];
$success = "";

$role_id = $_SESSION['role_id'];
$user_id = $_SESSION['user_id'];
$store_id_session = $_SESSION['store_id'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $store_id = $role_id == 2 ? $store_id_session : $_POST['store_id']; // Manager can't override
    $expense_type = $_POST['expense_type'];
    $description = $_POST['description'];
    $amount = $_POST['amount'];
    $expense_date = $_POST['expense_date'];
    $added_by = $user_id;
    $attachment_path = null;

    if (empty($store_id) || empty($expense_type) || empty($amount) || empty($expense_date)) {
        $errors[] = "Please fill in all required fields.";
    }

    // Handle file upload
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../../uploads/expenses/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

        $file_tmp = $_FILES['attachment']['tmp_name'];
        $file_name = basename($_FILES['attachment']['name']);
        $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
        $new_file_name = uniqid('expense_') . '.' . $file_ext;
        $upload_path = $upload_dir . $new_file_name;

        if (move_uploaded_file($file_tmp, $upload_path)) {
            $attachment_path = $new_file_name;
        } else {
            $errors[] = "File upload failed.";
        }
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO expenses (store_id, expense_type, description, amount, expense_date, attachment_path, added_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("issdssi", $store_id, $expense_type, $description, $amount, $expense_date, $attachment_path, $added_by);

        if ($stmt->execute()) {
            // Audit Log
            $details = "Added expense: Type=$expense_type, Amount=MWK $amount, StoreID=$store_id";
            $device = $_SERVER['HTTP_USER_AGENT'];
            $log = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id, device_info) VALUES (?, 'CREATE', ?, NOW(), 'expenses', ?, ?)");
            $log->bind_param("isis", $user_id, $details, $role_id, $device);
            $log->execute();
            $log->close();

            $success = "✅ Expense added successfully.";
            $_POST = [];
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
    }
}

$stores = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL")->fetch_all(MYSQLI_ASSOC);
$today = date('Y-m-d');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Expense - Digital POS</title>
    <style>
        body, html {
            margin: 0;
            padding: 10;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
        }

        .overlay {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: -1;
        }

        .content {
            margin: 80px auto;
            max-width: 600px;
            padding: 30px 40px;
            background: rgba(255,255,255,0.08);
            border-radius: 20px;
            backdrop-filter: blur(15px);
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }

        h2 { text-align: center; margin-bottom: 25px; }

        label {
            display: block;
            margin-bottom: 6px;
            font-weight: bold;
        }

        input, select, textarea {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 10px;
            border: none;
            background: rgba(255,255,255,0.15);
            color: black;
            font-size: 15px;
        }

        textarea { resize: vertical; }

        input[type="file"] { padding: 8px; }

        .submit-btn {
            width: 100%;
            padding: 12px;
            background: #ff6f00;
            border: none;
            border-radius: 25px;
            color: white;
            font-weight: bold;
            font-size: 16px;
            cursor: pointer;
        }

        .submit-btn:hover { background: #00994d; }

        .alert {
            padding: 12px 16px;
            margin-bottom: 20px;
            border-radius: 10px;
        }

        .alert-error { background: rgba(255, 50, 50, 0.3); }

        .alert-success { background: rgba(0, 255, 127, 0.3); }

        .preview { margin-bottom: 15px; }

        .preview a {
            color: #00ccff;
            text-decoration: underline;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Add New Expense</h2>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <ul><?php foreach ($errors as $error): ?><li><?= htmlspecialchars($error) ?></li><?php endforeach; ?></ul>
        </div>
    <?php elseif ($success): ?>
        <div class="alert alert-success"><?= $success; ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" id="expense-form">
        <?php if ($role_id == 1): ?>
            <label for="store_id">Store *</label>
            <select name="store_id" id="store_id" required>
                <option value="">-- Select Store --</option>
                <?php foreach ($stores as $store): ?>
                    <option value="<?= $store['id'] ?>" <?= (@$_POST['store_id'] == $store['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($store['store_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        <?php else: ?>
            <input type="hidden" name="store_id" value="<?= $store_id_session ?>">
        <?php endif; ?>

        <label for="expense_type">Expense Type *</label>
        <select name="expense_type" id="expense_type" required>
            <option value="">-- Select Type --</option>
            <?php
            $types = ['Utility', 'Transport', 'Supplies', 'Other'];
            foreach ($types as $type): ?>
                <option value="<?= $type ?>" <?= (@$_POST['expense_type'] === $type) ? 'selected' : '' ?>><?= $type ?></option>
            <?php endforeach; ?>
        </select>

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

        <label for="amount">Amount (MWK) *</label>
        <input type="number" step="0.01" min="0" name="amount" required value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>">

        <label for="expense_date">Expense Date *</label>
        <input type="date" name="expense_date" value="<?= htmlspecialchars($_POST['expense_date'] ?? $today) ?>" required>

        <label for="attachment">Attachment (optional)</label>
        <input type="file" name="attachment" id="attachment" accept=".pdf,.jpg,.jpeg,.png">
        <div class="preview" id="file-preview" style="display:none;"></div>

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

<script>
document.getElementById('attachment').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('file-preview');
    if (file) {
        preview.innerHTML = `Selected: <strong>${file.name}</strong>`;
        preview.style.display = 'block';
    } else {
        preview.innerHTML = '';
        preview.style.display = 'none';
    }
});
</script>
</body>
</html>
