<?php
header("Content-Type: application/json; charset=UTF-8");
require_once "db.php"; // الاتصال بقاعدة البيانات

$data = json_decode(file_get_contents("php://input"), true);

if (!$data) {
    echo json_encode(["status" => "error", "message" => "❌ لم يتم استلام البيانات"]);
    exit;
}

// استخراج الحقول من النموذج
$project_id     = intval($data['project_id'] ?? 0);
$emp_id         = intval($data['employee_id'] ?? 0);
$custody_date   = trim($data['dateAddCstody'] ?? '');
$custody_amount = floatval($data['advance_amount'] ?? 0);
$notes          = trim($data['notes'] ?? '');
$attachment     = trim($data['AttachmentPath'] ?? '');

// التحقق من الحقول المطلوبة
if ($project_id === 0 || $emp_id === 0 || $custody_date === "" || $custody_amount <= 0) {
    echo json_encode(["status" => "error", "message" => "⚠️ كل الحقول المطلوبة يجب أن تكون ممتلئة"]);
    exit;
}

// تحويل الحقول الفارغة إلى NULL
$notes      = $notes === '' ? null : $notes;
$attachment = $attachment === '' ? null : $attachment;

// تحضير الاستعلام
$sql = "INSERT INTO custodyMH (PID, EmpID, CDate, CAmount, CNotes, AttachmentPath)
        VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iisdss", $project_id, $emp_id, $custody_date, $custody_amount, $notes, $attachment);

if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "✅ تم إضافة العهدة بنجاح", "custody_id" => $stmt->insert_id]);
} else {
    echo json_encode(["status" => "error", "message" => "❌ خطأ أثناء الإضافة: " . $stmt->error]);
}

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