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

// استقبال البيانات من الطلب
$data = json_decode(file_get_contents("php://input"), true);
$PID = intval($data['PID'] ?? 0);

// التحقق من رقم المشروع
if ($PID === 0) {
    echo json_encode([
        "status" => "error",
        "message" => "❌ لم يتم تحديد رقم المشروع"
    ]);
    exit;
}

// جلب بيانات المشروع من جدول PrjectsMH
$stmt1 = $conn->prepare("
    SELECT 
        id, 
        project_name, 
        project_owner, 
        project_status, 
        project_location, 
        project_cost, 
        project_duration, 
        created_at, 
        AttachmentPath 
    FROM PrjectsMH 
    WHERE id = ?
");
$stmt1->bind_param("i", $PID);
$stmt1->execute();
$projectResult = $stmt1->get_result()->fetch_assoc();
$stmt1->close();

// التحقق من وجود المشروع
if (!$projectResult) {
    echo json_encode([
        "status" => "error",
        "message" => "❌ المشروع غير موجود"
    ]);
    exit;
}

// جلب بنود المشروع من جدول ProjectTermsMH
$stmt2 = $conn->prepare("
   SELECT  
    id,  
    PID,  
    item_name,  
    unit,  
    quantity,  
    price,  
    total,  
    notes,  
    created_at  
FROM ProjectTermsMH  
WHERE PID = ?  
ORDER BY created_at DESC, id DESC;
");
$stmt2->bind_param("i", $PID);
$stmt2->execute();
$termsResult = $stmt2->get_result();

$terms = [];
while ($row = $termsResult->fetch_assoc()) {
    $terms[] = $row;
}
$stmt2->close();

// إخراج البيانات بصيغة JSON
echo json_encode([
    "status" => "success",
    "project" => $projectResult,
    "terms" => $terms
]);

$conn->close();
?>
