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

// جلب بيانات العملاء
$customers = $pdo->query("
    SELECT 
        c.customer_id, 
        c.name, 
        (COALESCE(SUM(t.debit), 0) - COALESCE(SUM(t.credit), 0)) as balance
    FROM customers c
    LEFT JOIN customer_transactions t ON c.customer_id = t.customer_id
    WHERE c.status = 'Active'
    GROUP BY c.customer_id
")->fetchAll();

// جلب الصناديق
$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();
        
        $customer_id    = $_POST['customer_id'];
        $cashbox_id     = 1; 
        $amount         = $_POST['amount'];
        $payment_method = $_POST['payment_method'];
        $notes          = $_POST['notes']; 
        $voucher_date   = $_POST['voucher_date'];
        $user_id        = $_SESSION['user_id'];

        // 1. إدراج السند في جدول receipt_vouchers
        $stmt = $pdo->prepare("INSERT INTO receipt_vouchers (customer_id, amount, cashbox_id, payment_method, voucher_date, notes, user_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'active')");
        $stmt->execute([$customer_id, $amount, $cashbox_id, $payment_method, $voucher_date, $notes, $user_id]);
        $receipt_id = $pdo->lastInsertId();

        // 2. تحديث كشف حساب العميل (دمج الملاحظات هنا)
        $full_description = "Payment Received - Voucher #$receipt_id" . ($notes ? " ($notes)" : "");
        $stmt_cust = $pdo->prepare("INSERT INTO customer_transactions (customer_id, debit, credit, trans_date, description, user_id) VALUES (?, 0, ?, ?, ?, ?)");
        $stmt_cust->execute([$customer_id, $amount, $voucher_date, $full_description, $user_id]);

        // 3. القيود اليومية العامة (دمج الملاحظات هنا أيضاً)
        $daily_desc = "Receipt Voucher #$receipt_id - " . $notes;
        $stmt_daily = $pdo->prepare("INSERT INTO daily_transactions (trans_type, ref_id, debit, credit, description, trans_date, user_id) VALUES ('customer', ?, 0, ?, ?, ?, ?)");
        $stmt_daily->execute([$customer_id, $amount, $daily_desc, $voucher_date, $user_id]);

        // 4. تحديث رصيد الصندوق
        $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: receive.php?success=1");
        exit;

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Receipt 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: #1e293b; 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: #10b981; border: none; padding: 12px; font-weight: 700; width: 100%; border-radius: 8px; transition: 0.3s; cursor: pointer; }
        .btn-save:hover { background: #059669; transform: translateY(-2px); }
        .amount-box { background: #f8fafc; padding: 20px; border-radius: 12px; border: 1px solid #e2e8f0; }
    </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="receive.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-edit me-1"></i> Created By: <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 Receipt Voucher</h4>
                            <small class="text-white-50">Authorized Financial 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-7">
                                <label class="section-title">Customer Name</label>
                                <select name="customer_id" class="js-search-customer form-control" required>
                                    <option value="">Search for a customer...</option>
                                    <?php foreach($customers as $c): ?>
                                        <option value="<?= $c['customer_id'] ?>">
                                            <?= htmlspecialchars($c['name']) ?> (Bal: <?= number_format($c['balance'], 2) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-5">
                                <label class="section-title">Deposit To (Cash Box)</label>
                            <select class="form-select shadow-sm bg-light" 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="amount-box mb-4">
                            <div class="row align-items-end">
                                <div class="col-md-8">
                                    <label class="section-title">Amount Received</label>
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-text bg-white border-end-0 text-success"><i class="fas fa-money-bill-wave"></i></span>
                                        <input type="number" step="0.01" name="amount" class="form-control border-start-0 fw-bold text-success" placeholder="0.00" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <label class="section-title">Payment Method</label>
                                    <select name="payment_method" class="form-select form-select-lg shadow-sm">
                                        <option value="Cash">Cash</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Cheque">Cheque</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="section-title">Description / Notes</label>
                            <textarea name="notes" class="form-control shadow-sm" rows="3" placeholder="Enter transaction details (e.g., Check number, bank name, etc.)"></textarea>
                        </div>

                        <button type="submit" name="save_voucher" class="btn btn-save text-white shadow-lg">
                            <i class="fas fa-check-double me-2"></i> AUTHORIZE & POST VOUCHER
                        </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-customer').select2({
            width: '100%',
            placeholder: "Select Customer"
        });
    });
</script>

</body>
</html>