<?php
header("Content-Type: application/json; charset=UTF-8");
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once "db.php"; // تأكد إن الملف ده فيه الاتصال الصحيح

// استقبال البيانات بصيغة JSON
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);

// تحقق من البيانات المطلوبة
if (
    !$data ||
    !isset($data['id']) || !is_numeric($data['id']) ||
    !isset($data['project_name']) ||
    !isset($data['project_owner']) ||
    !isset($data['project_status']) ||
    !isset($data['project_location']) ||
    !isset($data['project_cost']) ||
    !isset($data['project_duration'])
) {
    echo json_encode(["status" => "error", "message" => "❌ بيانات ناقصة أو غير صالحة"]);
    exit;
}

// استخراج القيم وتنسيقها
$id               = intval($data['id']);
$project_name     = trim($data['project_name']);
$project_owner    = trim($data['project_owner']);
$project_status   = trim($data['project_status']);
$project_location = trim($data['project_location']);
$project_cost     = floatval($data['project_cost']);
$project_duration = trim($data['project_duration']);
$attachment       = isset($data['AttachmentPath']) ? trim($data['AttachmentPath']) : "";

// ✅ تحديث البيانات
$sql = "UPDATE PrjectsMH 
        SET 
            project_name = ?, 
            project_owner = ?, 
            project_status = ?, 
            project_location = ?, 
            project_cost = ?, 
            project_duration = ?, 
            created_at = NOW(), 
            AttachmentPath = ?
        WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param(
    "ssssdssi",
    $project_name,
    $project_owner,
    $project_status,
    $project_location,
    $project_cost,
    $project_duration,
    $attachment,
    $id
);

// تنفيذ الاستعلام
if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "✅ تم تعديل المشروع بنجاح"]);
} else {
    echo json_encode(["status" => "error", "message" => "❌ فشل تعديل المشروع: " . $stmt->error]);
}

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