<?php
// 1. تشغيل الجلسة وتحديد نوع البيانات المرتجعة (JSON)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

include 'config.php';

// 🔒 2. فحص الأمان والصلاحيات (نظام الصفحات الخاص بك)
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'عفواً! يجب تسجيل الدخول أولاً.']);
    exit;
}

$user_id = $_SESSION['user_id'];
$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([$user_id, $current_page]);

if (!$stmt_perm->fetch()) {
    echo json_encode(['status' => 'error', 'message' => 'عفواً! لا تمتلك صلاحية لحفظ فواتير المشتريات.']);
    exit;
}

// 3. استقبال البيانات القادمة من شاشة أودو (fetch)
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// ... (باقي كود save_purchase.php اللي بيحفظ الفاتورة والمخزن اللي عملناه في الرد اللي فات بدون أي تغيير) ...
if (!$data || empty($data['cart'])) {
    echo json_encode(['status' => 'error', 'message' => 'بيانات الفاتورة فارغة أو غير صحيحة.']);
    exit;
}

try {
    $pdo->beginTransaction();

    $branch_id   = intval($data['branch_id'] ?? 1);
    $supplier_id = intval($data['supplier_id']);
    $total       = floatval($data['total_amount']);
    $paid        = floatval($data['paid_amount']);

    $stmt_inv = $pdo->prepare("INSERT INTO purchase_invoices (supplier_id, branch_id, total_amount, paid_amount, invoice_date) VALUES (?, ?, ?, ?, NOW())");
    $stmt_inv->execute([$supplier_id, $branch_id, $total, $paid]);
    $purchase_id = $pdo->lastInsertId();

    $due_amount = $total - $paid;
    if ($due_amount > 0) {
        $stmt_supplier = $pdo->prepare("UPDATE suppliers SET balance = balance + ? WHERE id = ?");
        $stmt_supplier->execute([$due_amount, $supplier_id]);
    }

    $stmt_item = $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, quantity, cost_price, total) VALUES (?, ?, ?, ?, ?)");
    
    $stmt_check_inv = $pdo->prepare("SELECT quantity FROM inventory WHERE branch_id = ? AND product_id = ?");
    $stmt_update_inv = $pdo->prepare("UPDATE inventory SET quantity = quantity + ? WHERE branch_id = ? AND product_id = ?");
    $stmt_insert_inv = $pdo->prepare("INSERT INTO inventory (branch_id, product_id, quantity) VALUES (?, ?, ?)");

    foreach ($data['cart'] as $item) {
        $product_id = intval($item['product_id']);
        $qty        = floatval($item['qty']);
        $cost       = floatval($item['cost_price']);
        $item_total = $qty * $cost;

        $stmt_item->execute([$purchase_id, $product_id, $qty, $cost, $item_total]);

        $stmt_check_inv->execute([$branch_id, $product_id]);
        $inv_exists = $stmt_check_inv->fetch();

        if ($inv_exists) {
            $stmt_update_inv->execute([$qty, $branch_id, $product_id]);
        } else {
            $stmt_insert_inv->execute([$branch_id, $product_id, $qty]);
        }
    }

    $pdo->commit();
    echo json_encode(['status' => 'success', 'purchase_id' => $purchase_id]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 'error', 'message' => 'فشل حفظ الحركة: ' . $e->getMessage()]);
}
?>