<?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('pay', 'add')) {
    header('Location: pay.php?error=no_permission');
    exit;
}

// 1. جلب بيانات الوكلاء مع أرصدتهم الحالية
// الرصيد = (إجمالي له - إجمالي عليه) أو العكس حسب نظامك المحاسبي
$agents = $pdo->query("
    SELECT 
        a.agent_id, 
        a.name, 
        (COALESCE(SUM(t.credit), 0) - COALESCE(SUM(t.debit), 0)) as balance
    FROM agents a
    LEFT JOIN agent_transactions t ON a.agent_id = t.agent_id
    WHERE a.status = 'Active'
    GROUP BY a.agent_id
")->fetchAll();

// 2. جلب الصناديق
$cash_boxes = $pdo->query("SELECT cashbox_id, cashbox_name FROM cash_boxes WHERE status = 'Active'")->fetchAll();

$message = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_voucher'])) {
    try {
        $pdo->beginTransaction();
        
        $payment_no     = $_POST['payment_no'];
        $pay_type       = $_POST['pay_type']; // 'agent' or 'expense'
        $agent_id       = $_POST['agent_id'] ?: null; 
        $cashbox_id     = 1; 
        $amount         = $_POST['amount'];
        $voucher_date   = $_POST['voucher_date'];
        $notes          = $_POST['notes']; 
        $user_id        = $_SESSION['user_id'];

        // أ. إدراج السند في جدول payment_vouchers
        $stmt = $pdo->prepare("INSERT INTO payment_vouchers (payment_no, pay_type, ref_id, amount, payment_date, description, user_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'active')");
        $stmt->execute([$payment_no, $pay_type, $agent_id, $amount, $voucher_date, $notes, $user_id]);
        $payment_id = $pdo->lastInsertId();

        // ب. إذا كان النوع سداد لوكيل، نقوم بتحديث كشف حساب الوكيل
        if ($pay_type == 'agent' && $agent_id) {
            $full_desc = "Payment Made - Voucher #$payment_no" . ($notes ? " ($notes)" : "");
            // في الصرف: الوكيل يكون مدين (Debit) لأننا أعطيناه مالاً
            $stmt_agent = $pdo->prepare("INSERT INTO agent_transactions (agent_id, debit, credit, trans_date, description, user_id) VALUES (?, ?, 0, ?, ?, ?)");
            $stmt_agent->execute([$agent_id, $amount, $voucher_date, $full_desc, $user_id]);
        }

        // ج. القيود اليومية العامة
        $daily_desc = "Payment Voucher #$payment_no - " . ($pay_type == 'agent' ? "Agent Payment" : "Expense") . " - " . $notes;
        $stmt_daily = $pdo->prepare("INSERT INTO daily_transactions (trans_type, ref_id, debit, credit, description, trans_date, user_id) VALUES ('agent', ?, ?, 0, ?, ?, ?)");
        $stmt_daily->execute([$agent_id, $amount, $daily_desc, $voucher_date, $user_id]);

        // د. تحديث رصيد الصندوق (خصم المبلغ)
        $stmt_box = $pdo->prepare("UPDATE cash_boxes SET current_balance = current_balance - ? WHERE cashbox_id = ?");
        $stmt_box->execute([$amount, $cashbox_id]);

        $pdo->commit();
        header("Location: pay.php?success=1");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        $message = "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}

// اقتراح رقم السند التالي
$last_no = $pdo->query("SELECT MAX(payment_no) FROM payment_vouchers")->fetchColumn();
$next_no = $last_no ? $last_no + 1 : 1001;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>New Payment Voucher</title>
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <style>
        body { background-color: #f1f5f9; font-family: 'Inter', sans-serif; }
        .voucher-card { background: #fff; border-radius: 15px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); border: none; }
        .voucher-header { background: #ef4444; color: #fff; padding: 20px; border-radius: 15px 15px 0 0; display: flex; justify-content: space-between; align-items: center; }
        .section-title { font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px; display: block; }
        .btn-save { background: #ef4444; border: none; padding: 12px; font-weight: 700; width: 100%; border-radius: 8px; transition: 0.3s; cursor: pointer; color: white; }
        .btn-save:hover { background: #dc2626; transform: translateY(-2px); }
        .amount-box { background: #fef2f2; padding: 20px; border-radius: 12px; border: 1px solid #fee2e2; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-9">
            
            <div class="mb-3 d-flex justify-content-between align-items-center">
                <a href="pay.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i> Back to List</a>
                <div class="text-muted small">
                    <i class="fas fa-user-shield me-1"></i> Auditor: <strong><?= htmlspecialchars($_SESSION['username'] ?? 'User') ?></strong>
                </div>
            </div>

            <div class="voucher-card">
                <form method="POST">
                    <div class="voucher-header">
                        <div>
                            <h4 class="mb-0 text-uppercase">New Payment Voucher</h4>
                            <small class="text-white-50">Financial Disbursement Entry</small>
                        </div>
                        <div class="text-end">
                            <span class="section-title text-white-50">Voucher Date</span>
                            <input type="date" name="voucher_date" value="<?= date('Y-m-d') ?>" class="form-control form-control-sm border-0 shadow-sm">
                        </div>
                    </div>

                    <div class="p-4 p-md-5">
                        <?= $message ?>

                        <div class="row mb-4">
                            <div class="col-md-4">
                                <label class="section-title">Voucher Number</label>
                                <input type="number" name="payment_no" value="<?= $next_no ?>" class="form-control shadow-sm" required>
                            </div>
                            <div class="col-md-4">
                                <label class="section-title">Payment Type</label>
                                <select name="pay_type" id="pay_type" class="form-select shadow-sm" required>
                                    <option value="expense">General Expense</option>
                                    <option value="agent">Agent Settlement</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="section-title">From (Cash Box)</label>
                            <select name="cashbox_id_display" class="form-select shadow-sm" style="height: 40px;" disabled>
    <?php foreach($cash_boxes as $box): ?>
        <option value="<?= $box['cashbox_id'] ?>" <?= $box['cashbox_id'] == 1 ? 'selected' : '' ?>>
            <?= htmlspecialchars($box['cashbox_name']) ?>
        </option>
    <?php endforeach; ?>
</select>
<input type="hidden" name="cashbox_id" value="1">
                            </div>
                        </div>

                        <div class="row mb-4" id="agent_section" style="display:none;">
                            <div class="col-md-12">
                                <label class="section-title">Agent Name</label>
                                <select name="agent_id" class="js-search-agent form-control">
                                    <option value="">Search for an agent...</option>
                                    <?php foreach($agents as $a): ?>
                                        <option value="<?= $a['agent_id'] ?>">
                                            <?= htmlspecialchars($a['name']) ?> (Due: <?= number_format($a['balance'], 2) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="amount-box mb-4">
                            <div class="row align-items-end">
                                <div class="col-md-12">
                                    <label class="section-title">Amount to Pay</label>
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-text bg-white border-end-0 text-danger"><i class="fas fa-hand-holding-usd"></i></span>
                                        <input type="number" step="0.01" name="amount" class="form-control border-start-0 fw-bold text-danger" placeholder="0.00" required>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="section-title">Payment Description / Purpose</label>
                            <textarea name="notes" class="form-control shadow-sm" rows="3" placeholder="Describe the reason for payment..."></textarea>
                        </div>

                        <button type="submit" name="save_voucher" class="btn btn-save shadow-lg">
                            <i class="fas fa-file-export me-2"></i> EXECUTE PAYMENT & UPDATE LEDGERS
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </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() {
        $('.js-search-agent').select2({
            width: '100%',
            placeholder: "Select Agent"
        });

        $('#pay_type').on('change', function() {
            if ($(this).val() === 'agent') {
                $('#agent_section').slideDown();
                $('.js-search-agent').prop('required', true);
            } else {
                $('#agent_section').slideUp();
                $('.js-search-agent').prop('required', false);
            }
        });
    });
</script>

</body>
</html>