<?php
header("Content-Type: application/json; charset=UTF-8");
require_once "db.php";

// قراءة JSON من الجسم
$data = json_decode(file_get_contents("php://input"), true);
if (!$data) {
    echo json_encode(["status" => "error", "message" => "❌ لم يتم استلام البيانات"]);
    exit;
}

// استخراج الحقول
$PID       = intval($data['project_id2nd'] ?? 0);
$item_name = trim($data['item_name'] ?? '');
$unit      = trim($data['unit'] ?? '');
$quantity  = floatval($data['quantity'] ?? 0);
$price     = floatval($data['price'] ?? 0);
$total     = floatval($data['total'] ?? 0);
$notes     = trim($data['notes'] ?? '');

// التحقق من الحقول الأساسية
if ($PID === 0 || $item_name === '' || $unit === '' || $quantity === 0 || $price === 0) {
    echo json_encode(["status" => "error", "message" => "⚠️ الرجاء إدخال جميع بيانات البند المطلوبة"]);
    exit;
}

// إدراج البند مع تعيين created_at من MySQL نفسه
$sql  = "INSERT INTO ProjectTermsMH
         (PID, item_name, unit, quantity, price, total, notes, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
$stmt = $conn->prepare($sql);
$stmt->bind_param("issddds", $PID, $item_name, $unit, $quantity, $price, $total, $notes);

// تنفيذ والإرسال
if ($stmt->execute()) {
    echo json_encode([
        "status"  => "success",
        "message" => "✅ تم حفظ البند بنجاح",
        "data"    => [
            "item_name" => $item_name,
            "unit"      => $unit,
            "quantity"  => $quantity,
            "price"     => $price,
            "total"     => $total,
            "notes"     => $notes
        ]
    ]);
} else {
    echo json_encode(["status" => "error", "message" => "❌ خطأ في الحفظ: " . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
