<?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';

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

$errors = [];

// 1. Fetch Expense Categories
$expense_types = $pdo->query("SELECT expense_id, expense_name FROM expenses WHERE status = 'active' ORDER BY expense_name ASC")->fetchAll();

// 2. Fetch Cash Boxes
$boxes = $pdo->query("SELECT cashbox_id, cashbox_name, current_balance FROM cash_boxes WHERE status = 'active' ORDER BY cashbox_name ASC")->fetchAll();

// Logic for AJAX Request (حساب الصافي المستحق: له - عليه)
if (isset($_GET['get_due']) && !empty($_GET['expense_id'])) {
    $eid = $_GET['expense_id'];
    
    $stmt = $pdo->prepare("
        SELECT 
            SUM(CASE WHEN amount < 0 THEN ABS(amount) ELSE 0 END) as total_due,
            SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as total_paid
        FROM expense_transactions 
        WHERE expense_id = ? AND status = 'active'
    ");
    $stmt->execute([$eid]);
    $res = $stmt->fetch();
    
    $total_due  = (float)($res['total_due'] ?? 0);
    $total_paid = (float)($res['total_paid'] ?? 0);
    $net_due    = $total_due - $total_paid; // الصافي المتبقي بذمته

    echo json_encode([
        'total_due'  => $total_due,
        'total_paid' => $total_paid,
        'net_due'    => $net_due
    ]);
    exit;
}

// Handle Form Submission
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 (!$cashbox_id) $errors[] = "Please select a cash box.";
    if ($amount <= 0) $errors[] = "Amount must be greater than zero.";

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $stmtBox = $pdo->prepare("SELECT current_balance, cashbox_name FROM cash_boxes WHERE cashbox_id = ? FOR UPDATE");
            $stmtBox->execute([$cashbox_id]);
            $box = $stmtBox->fetch();

            if ($box['current_balance'] < $amount) {
                throw new Exception("Insufficient balance in " . $box['cashbox_name']);
            }

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

            $sqlUpdateBox = "UPDATE cash_boxes SET current_balance = current_balance - ? WHERE cashbox_id = ?";
            $pdo->prepare($sqlUpdateBox)->execute([$amount, $cashbox_id]);

            $pdo->commit();
            header("Location: expenses.php?msg=added");
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add New Expense (Paid)</title>
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
   
    <link href="../assets/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="../assets/css/1/select2-bootstrap-5-theme.min.css" />

    <style>
        body { background:#f8fafc; font-family:'Inter', sans-serif; }
        .form-card { background:#fff; border-radius:12px; border:1px solid #e2e8f0; max-width: 800px; margin: 40px auto; padding: 30px; }
        .form-label { font-weight: 600; font-size: 13px; color: #475569; }
        
        /* Due Info Styling */
        .balance-card { background: #f1f5f9; border-radius: 8px; padding: 15px; display: none; margin-bottom: 20px; border: 1px dashed #cbd5e1; }
        .balance-item { text-align: center; }
        .balance-label { font-size: 11px; text-transform: uppercase; color: #64748b; font-weight: bold; }
        .balance-value { font-size: 16px; font-weight: 700; }
        
        .select2-container--bootstrap-5 .select2-selection { font-size: 14px; border-radius: 8px; }
    </style>
</head>
<body>

<div class="container">
    <div class="form-card shadow-sm">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="fw-bold m-0 text-success"><i class="fas fa-money-bill-wave me-2"></i>Record Payment</h4>
                <p class="text-muted small mb-0">Pay balance for a person or category</p>
            </div>
            <a href="expenses.php" class="btn btn-light btn-sm border">Cancel</a>
        </div>

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

        <div id="balance_section" class="balance-card">
            <div class="row">
                <div class="col-4 balance-item border-end">
                    <div class="balance-label">Total Due (له)</div>
                    <div class="balance-value text-danger" id="val_total_due">0.00</div>
                </div>
                <div class="col-4 balance-item border-end">
                    <div class="balance-label">Previously Paid (عليه)</div>
                    <div class="balance-value text-success" id="val_total_paid">0.00</div>
                </div>
                <div class="col-4 balance-item">
                    <div class="balance-label">Net Balance (الصافي)</div>
                    <div class="balance-value text-primary" id="val_net_due">0.00</div>
                </div>
            </div>
        </div>

        <form method="POST" id="expenseForm">
            <div class="row g-3">
                <div class="col-md-12">
                    <label class="form-label">Select Person / Expense Category</label>
                    <select name="expense_id" id="expense_id" class="form-select select2-enable" required>
                        <option value="">-- Search by Name --</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">Transaction 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">Amount to Pay Now</label>
                    <div class="input-group">
                        <span class="input-group-text bg-success text-white fw-bold">$</span>
                        <input type="number" name="amount" id="amount_input" step="0.01" class="form-control" placeholder="0.00" required>
                    </div>
                </div>

                <div class="col-md-12">
                    <label class="form-label">Payment Source (Cash Box)</label>
                    <select name="cashbox_id" id="cashbox_id" class="form-select select2-enable" required>
                        <option value="">-- Select Source Box --</option>
                        <?php foreach ($boxes as $b): ?>
                            <option value="<?= $b['cashbox_id'] ?>">
                                <?= htmlspecialchars($b['cashbox_name']) ?> (Available: <?= number_format($b['current_balance'], 2) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label">Description / Notes</label>
                    <textarea name="description" class="form-control" rows="2" placeholder="Write payment details..."></textarea>
                </div>

                <div class="col-12 mt-4">
                    <button type="submit" class="btn btn-success w-100 py-2 fw-bold shadow-sm">
                        <i class="fas fa-save me-2"></i> Save Payment
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="../assets/js/jquery-3.6.0.min.js"></script>
<script src="../assets/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    $('.select2-enable').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });

    $('#expense_id').on('change', function() {
        const expenseId = $(this).val();
        if (expenseId) {
            $.ajax({
                url: window.location.href,
                type: 'GET',
                data: { get_due: 1, expense_id: expenseId },
                dataType: 'json',
                success: function(data) {
                    // Update values
                    $('#val_total_due').text(data.total_due.toLocaleString(undefined, {minimumFractionDigits: 2}));
                    $('#val_total_paid').text(data.total_paid.toLocaleString(undefined, {minimumFractionDigits: 2}));
                    $('#val_net_due').text(data.net_due.toLocaleString(undefined, {minimumFractionDigits: 2}));
                    
                    // Show the balance section
                    $('#balance_section').slideDown();

                    // Optional: Auto-fill the amount input with the net due
                    if(data.net_due > 0) {
                        $('#amount_input').val(data.net_due);
                    } else {
                        $('#amount_input').val('');
                    }
                }
            });
        } else {
            $('#balance_section').slideUp();
        }
    });
});
</script>

</body>
</html>