<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

if (!can('expenses', 'add')) {
    die('Access Denied');
}

$errors = [];
$expense_types = $pdo->query("SELECT expense_id, expense_name FROM expenses WHERE status = 'active' ORDER BY expense_name ASC")->fetchAll();
$boxes = $pdo->query("SELECT cashbox_id, cashbox_name FROM cash_boxes WHERE status = 'active' ORDER BY cashbox_name ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $expense_id  = $_POST['expense_id'] ?? '';
    $cashbox_id  = $_POST['cashbox_id'] ?? '';
    $amount      = (float)($_POST['amount'] ?? 0);
    $trans_date  = $_POST['trans_date'] ?? date('Y-m-d');
    $description = trim($_POST['description'] ?? '');
    $user_id     = $_SESSION['user_id'];

    if (!$expense_id) $errors[] = "Please select an expense category.";
    if ($amount <= 0) $errors[] = "Amount must be greater than zero.";

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            $negative_amount = $amount * -1; // Due is negative

            $sqlInsert = "INSERT INTO expense_transactions (expense_id, amount, trans_date, description, box_id, user_id, status) 
                          VALUES (?, ?, ?, ?, ?, ?, 'active')";
            $pdo->prepare($sqlInsert)->execute([$expense_id, $negative_amount, $trans_date, $description, $cashbox_id, $user_id]);

            $pdo->commit();
            header("Location: expenses.php?msg=added_due");
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Due Expense</title>
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <style>
        body { background:#f8fafc; font-family:'Inter', sans-serif; }
        .form-card { background:#fff; border-radius:12px; border:1px solid #e2e8f0; max-width: 700px; margin: 40px auto; padding: 30px; }
        .form-label { font-weight: 600; font-size: 13px; color: #475569; }
    </style>
</head>
<body>
<div class="container">
    <div class="form-card shadow-sm">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h4 class="fw-bold m-0 text-warning">Add New (Due) Expense</h4>
            <a href="expenses.php" class="btn btn-light btn-sm border">Cancel</a>
        </div>

        <?php if (!empty($errors)): ?><div class="alert alert-danger"><ul><?php foreach($errors as $er) echo "<li>$er</li>"; ?></ul></div><?php endif; ?>

        <form method="POST">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Date</label>
                    <input type="date" name="trans_date" value="<?= date('Y-m-d') ?>" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Category</label>
                    <select name="expense_id" class="form-select" required>
                        <option value="">-- Select Category --</option>
                        <?php foreach ($expense_types as $et): ?>
                            <option value="<?= $et['expense_id'] ?>"><?= htmlspecialchars($et['expense_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Related Cash Box</label>
                    <select name="cashbox_id" class="form-select" required>
                        <?php foreach ($boxes as $b): ?>
                            <option value="<?= $b['cashbox_id'] ?>"><?= htmlspecialchars($b['cashbox_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Due Amount</label>
                    <div class="input-group">
                        <span class="input-group-text">$</span>
                        <input type="number" name="amount" step="0.01" class="form-control" placeholder="0.00" required>
                    </div>
                </div>
                <div class="col-12">
                    <label class="form-label">Notes</label>
                    <textarea name="description" class="form-control" rows="3"></textarea>
                </div>
                <div class="col-12 mt-4">
                    <button type="submit" class="btn btn-warning w-100 py-2 fw-bold text-dark">
                        <i class="fas fa-save me-2"></i> Save as Due
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
</body>
</html>