<?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;
}

// استخراج البيانات من JSON
$PID             = intval($data['project_id'] ?? 0);
$RafranceNumber  = trim($data['invoice_number'] ?? '');
$value           = floatval($data['amount'] ?? 0);
$date            = trim($data['date'] ?? '');
$notes           = trim($data['notes'] ?? '');
$AttachmentPath  = trim($data['attachment'] ?? ''); // ✅ جديد: اختياري

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

// تنفيذ الإدخال
$sql = "INSERT INTO revenuesMH (PID, RafranceNumber, value, date, notes, AttachmentPath)
        VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("isdsss", $PID, $RafranceNumber, $value, $date, $notes, $AttachmentPath);

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

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