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

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

$expense_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$errors = [];
$success = "";

// Fetch existing expense
$stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ? AND deleted_at IS NULL");
$stmt->bind_param("i", $expense_id);
$stmt->execute();
$result = $stmt->get_result();
$expense = $result->fetch_assoc();

if (!$expense) {
    echo "<div class='content'><p>Expense not found.</p></div>";
    include('../../includes/footer.php');
    exit();
}

// Update handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $store_id = $_POST['store_id'];
    $expense_type = $_POST['expense_type'];
    $description = $_POST['description'];
    $amount = $_POST['amount'];
    $expense_date = $_POST['expense_date'];
    $attachment_path = $expense['attachment_path'];

    if (empty($store_id) || empty($expense_type) || empty($amount) || empty($expense_date)) {
        $errors[] = "All required fields must be filled.";
    }

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

        $ext = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
        $new_file = uniqid('expense_') . '.' . $ext;
        $tmp_name = $_FILES['attachment']['tmp_name'];

        if (move_uploaded_file($tmp_name, $upload_dir . $new_file)) {
            $attachment_path = $new_file;
        } else {
            $errors[] = "File upload failed.";
        }
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("UPDATE expenses SET store_id = ?, expense_type = ?, description = ?, amount = ?, expense_date = ?, attachment_path = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param("issdssi", $store_id, $expense_type, $description, $amount, $expense_date, $attachment_path, $expense_id);

        if ($stmt->execute()) {
            $success = "✅ Expense updated successfully.";
            $expense = array_merge($expense, $_POST);
            $expense['attachment_path'] = $attachment_path;
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
    }
}

// Stores dropdown
$stores = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL")->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Expense</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/bg.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 {
            max-width: 600px;
            margin: 60px auto;
            padding: 30px 40px;
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(15px);
            border-radius: 20px;
            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: white;
        }
        .submit-btn {
            width: 100%;
            padding: 12px;
            background: #00cc66;
            border: none;
            border-radius: 25px;
            color: white;
            font-weight: bold;
            font-size: 16px;
            cursor: pointer;
        }
        .submit-btn:hover {
            background: #00994d;
        }
        .alert {
            padding: 10px 15px;
            margin-bottom: 20px;
            border-radius: 10px;
            font-size: 14px;
        }
        .alert-error {
            background: rgba(255, 50, 50, 0.3);
        }
        .alert-success {
            background: rgba(0, 255, 127, 0.3);
        }
        .file-preview {
            margin-bottom: 15px;
        }
        .file-preview a {
            color: #00ccff;
            text-decoration: underline;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Edit Expense</h2>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <?= implode('<br>', $errors); ?>
        </div>
    <?php elseif ($success): ?>
        <div class="alert alert-success">
            <?= $success; ?>
        </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <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'] ?>" <?= $expense['store_id'] == $store['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($store['store_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

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

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

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

        <label for="expense_date">Expense Date</label>
        <input type="date" name="expense_date" value="<?= $expense['expense_date'] ?: date('Y-m-d') ?>" required>

        <?php if (!empty($expense['attachment_path'])): ?>
            <div class="file-preview">
                Current Attachment:
                <a href="../../uploads/expenses/<?= $expense['attachment_path'] ?>" target="_blank">View File</a>
            </div>
        <?php endif; ?>

        <label for="attachment">Replace Attachment</label>
        <input type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png">

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

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