<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
include_once 'db_connect.php';

// وظيفة لتصغير حجم الصورة
function compressImage($source, $destination, $quality) {
    $info = getimagesize($source);
    if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);
    elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source);
    elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);
    
    imagejpeg($image, $destination, $quality);
    
    while(filesize($destination) > 200 * 1024 && $quality > 10) {
        $quality -= 5;
        imagejpeg($image, $destination, $quality);
    }
    return $destination;
}

// الحصول على البيانات
$data = $_POST;
if (empty($data)) {
    $data = json_decode(file_get_contents("php://input"), true);
}

$user_id = isset($data['user_id']) ? $data['user_id'] : null;

if ($user_id) {
    try {
        $conn->beginTransaction();

        // 1. تحديث البيانات الأساسية في جدول users
        if (isset($data['full_name'])) {
            $sql_user = "UPDATE users SET 
                            full_name = COALESCE(NULLIF(?, ''), full_name), 
                            phone = COALESCE(NULLIF(?, ''), phone), 
                            address = COALESCE(NULLIF(?, ''), address) 
                         WHERE id = ?";
            $stmt_user = $conn->prepare($sql_user);
            $stmt_user->execute([
                $data['full_name'],
                $data['phone'],
                $data['address'],
                $user_id
            ]);
        }

        // 2. معالجة تحديث الصورة
        $profile_image_sql = "";
        $profile_image_param = [];
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
            $target_dir = "uploads/patients/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            
            $file_ext = pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION);
            $file_name = "patient_" . $user_id . "_" . time() . "." . $file_ext;
            $target_file = $target_dir . $file_name;
            
            compressImage($_FILES["profile_image"]["tmp_name"], $target_file, 80);
            
            $profile_image_sql = ", profile_image = ?";
            $profile_image_param = [$target_file];
        }

        // 3. تحديث البيانات التفصيلية في جدول patients (مع حماية الحقول من الفراغ)
        // NULLIF(?, '') تحول الفراغ القادم من Flutter إلى NULL
        // COALESCE(..., original_column) تأخذ القيمة الأصلية إذا كانت القيمة الجديدة NULL
        $sql_patient = "UPDATE patients SET 
                            birth_date = COALESCE(NULLIF(?, ''), birth_date), 
                            gender = COALESCE(NULLIF(?, ''), gender), 
                            blood_group = COALESCE(NULLIF(?, ''), blood_group), 
                            weight = COALESCE(NULLIF(?, ''), weight), 
                            height = COALESCE(NULLIF(?, ''), height), 
                            has_drug_allergy = COALESCE(NULLIF(?, ''), has_drug_allergy), 
                            what_medications = ?,
                            takes_allergy_meds = COALESCE(NULLIF(?, ''), takes_allergy_meds), 
                            allergy_treatment = ?,
                            has_chronic_diseases = COALESCE(NULLIF(?, ''), has_chronic_diseases), 
                            chronic_diseases = ?,
                            takes_chronic_meds = COALESCE(NULLIF(?, ''), takes_chronic_meds), 
                            chronic_meds = ?,
                            has_medical_reports = COALESCE(NULLIF(?, ''), has_medical_reports), 
                            additional_notes = ?" . $profile_image_sql . "
                        WHERE user_id = ?";
        
        $stmt_patient = $conn->prepare($sql_patient);

        // ترتيب الباراميترات حسب الاستعلام أعلاه
        $params = [
            $data['birth_date'] ?? '',
            $data['gender'] ?? '',
            $data['blood_group'] ?? '',
            $data['weight'] ?? '',
            $data['height'] ?? '',
            $data['has_drug_allergy'] ?? '',
            $data['what_medications'] ?? '',
            $data['takes_allergy_meds'] ?? '',
            $data['allergy_treatment'] ?? '',
            $data['has_chronic_diseases'] ?? '',
            $data['chronic_diseases'] ?? '',
            $data['takes_chronic_meds'] ?? '',
            $data['chronic_meds'] ?? '',
            $data['has_medical_reports'] ?? '',
            $data['additional_notes'] ?? ''
        ];
        
        if (!empty($profile_image_param)) {
            $params = array_merge($params, $profile_image_param);
        }
        $params[] = $user_id;

        $stmt_patient->execute($params);

        $conn->commit();
        echo json_encode(["status" => "success", "message" => "تم تحديث البيانات بنجاح"]);

    } catch (PDOException $e) {
        if ($conn->inTransaction()) $conn->rollBack();
        echo json_encode(["status" => "error", "message" => "خطأ في التحديث: " . $e->getMessage()]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "معرف المستخدم مفقود"]);
}
?>