<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
include 'config.php';

// 1. الحماية والتحقق من الصلاحية
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }
$current_page = basename($_SERVER['PHP_SELF']);
$stmt_perm = $pdo->prepare("SELECT up.id FROM user_permissions up JOIN pages p ON up.page_id = p.id WHERE up.user_id = ? AND p.page_url = ?");
$stmt_perm->execute([$_SESSION['user_id'], $current_page]);
if (!$stmt_perm->fetch()) { die("<h2 style='text-align:center; margin-top:50px;'>عفواً، لا تملك صلاحية الوصول لهذه الصفحة</h2>"); }

// 2. معالجة الحفظ (AJAX POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if ($data['action'] == 'save') {
        try {
            $pdo->beginTransaction();
            
            // تسجيل الفاتورة
            $stmt = $pdo->prepare("INSERT INTO purchase_invoices (supplier_id, total_amount, paid_amount, next_payment_date, invoice_date) VALUES (?, ?, ?, ?, NOW())");
            $stmt->execute([$data['supplier_id'], $data['total'], $data['paid'], $data['next_date']]);
            $inv_id = $pdo->lastInsertId();

            // تسجيل الأصناف
            $stmt_items = $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, quantity, cost_price, total) VALUES (?, ?, ?, ?, ?)");
            foreach ($data['items'] as $item) {
                $item_total = $item['qty'] * $item['price'];
                $stmt_items->execute([$inv_id, $item['id'], $item['qty'], $item['price'], $item_total]);
            }

            // تحديث المديونية في جدول الموردين
            $rem = $data['total'] - $data['paid'];
            if ($rem > 0) {
                $pdo->prepare("UPDATE suppliers SET balance = balance + ? WHERE id = ?")->execute([$rem, $data['supplier_id']]);
            }
            $pdo->commit();
            echo json_encode(['status' => 'success']);
        } catch (Exception $e) { $pdo->rollBack(); echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]); }
        exit;
    }
}

$suppliers = $pdo->query("SELECT id, name FROM suppliers")->fetchAll(PDO::FETCH_ASSOC);
$products = $pdo->query("SELECT id, product_name FROM products")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    <title>فاتورة مشتريات مالية</title>
</head>
<body class="bg-light p-4">
<div class="card p-4 shadow-sm">
    <h4>إنشاء فاتورة مشتريات (تسوية مالية)</h4>
    <div class="row mt-3">
        <div class="col-md-4">
            <label>المورد</label>
            <select id="sup" class="form-select"><?php foreach($suppliers as $s): ?><option value="<?=$s['id']?>"><?=$s['name']?></option><?php endforeach; ?></select>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-md-3"><select id="prod" class="form-select"><?php foreach($products as $p): ?><option value="<?=$p['id']?>" data-name="<?=$p['product_name']?>"><?=$p['product_name']?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><input type="number" id="qty" class="form-control" placeholder="الكمية"></div>
        <div class="col-md-2"><input type="number" id="price" class="form-control" placeholder="السعر"></div>
        <div class="col-md-2"><button class="btn btn-primary" onclick="add()">إضافة</button></div>
    </div>

    <table class="table mt-4">
        <thead><tr><th>الصنف</th><th>الكمية</th><th>السعر</th><th>الإجمالي</th></tr></thead>
        <tbody id="cart_body"></tbody>
    </table>

    <div class="row mt-3 p-3 bg-white border rounded">
        <div class="col-md-3">الإجمالي: <h4 id="total_display">0.00</h4></div>
        <div class="col-md-3">
            <label>المبلغ المدفوع:</label>
            <input type="number" id="paid_amount" class="form-control" onkeyup="calcRemaining()">
        </div>
        <div class="col-md-3">
            <label>المتبقي (آجل):</label>
            <h4 id="remaining_display" class="text-danger">0.00</h4>
        </div>
        <div class="col-md-3">
            <label>ميعاد سداد المتبقي:</label>
            <input type="date" id="next_payment_date" class="form-control">
        </div>
    </div>
    <div class="mt-3"><button class="btn btn-success" onclick="save()">حفظ الفاتورة</button></div>
</div>

<script>
    let cart = [];
    function add() {
        let p = document.getElementById('prod');
        if(!p.value) return alert('اختر صنفاً');
        let item = { id: p.value, name: p.options[p.selectedIndex].dataset.name, qty: +document.getElementById('qty').value, price: +document.getElementById('price').value };
        cart.push(item);
        render();
    }
    function render() {
        let body = '', total = 0;
        cart.forEach(i => { body += `<tr><td>${i.name}</td><td>${i.qty}</td><td>${i.price}</td><td>${i.qty * i.price}</td></tr>`; total += (i.qty * i.price); });
        document.getElementById('cart_body').innerHTML = body;
        document.getElementById('total_display').innerText = total.toFixed(2);
        calcRemaining();
    }
    function calcRemaining() {
        let total = parseFloat(document.getElementById('total_display').innerText) || 0;
        let paid = parseFloat(document.getElementById('paid_amount').value) || 0;
        document.getElementById('remaining_display').innerText = (total - paid).toFixed(2);
    }
    async function save() {
        let total = parseFloat(document.getElementById('total_display').innerText);
        let paid = parseFloat(document.getElementById('paid_amount').value) || 0;
        let next_date = document.getElementById('next_payment_date').value;

        if ((total - paid) > 0 && !next_date) return alert('يجب تحديد ميعاد السداد للمبلغ المتبقي.');

        let res = await fetch('', {
            method: 'POST',
            body: JSON.stringify({ action: 'save', supplier_id: document.getElementById('sup').value, total: total, paid: paid, next_date: next_date, items: cart })
        });
        let data = await res.json();
        if(data.status == 'success') { alert('تم الحفظ بنجاح'); location.reload(); } else { alert(data.msg); }
    }
</script>
</body>
</html>