<?php
ob_start(); 
header("Content-Type: application/json; charset=UTF-8");
include 'db_connect.php';

// التأكد من وصول البيانات الأساسية
if (!isset($_POST['user_id']) || !isset($_POST['email'])) {
    echo json_encode(["status" => "error", "message" => "بيانات غير مكتملة"]);
    exit;
}

$user_id = $_POST['user_id'];
$email   = $_POST['email'];

try {
    // 1. فحص البريد الإلكتروني (هل هو مستخدم من قبل شخص آخر؟)
    $check_sql = "SELECT id FROM users WHERE email = ? AND id != ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->execute([$email, $user_id]);
    
    if ($check_stmt->fetch()) {
        echo json_encode(["status" => "error", "message" => "عذراً، هذا البريد مسجل لمستخدم آخر."]);
        exit;
    }

    $conn->beginTransaction();

    // --- [معالجة رفع الصورة] ---
    $profile_image_path = null;
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
        $target_dir = "uploads/doctors/";
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $file_extension = pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION);
        $new_filename = "doctor_" . $user_id . "_" . time() . "." . $file_extension;
        $target_file = $target_dir . $new_filename;

        if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $target_file)) {
            $profile_image_path = $target_file;
        }
    }

    // --- [2. تحديث جدول users] ---
    $password = $_POST['password'] ?? '';
    
    if (!empty($password)) {
        $sql_user = "UPDATE users SET full_name = ?, email = ?, phone = ?, password = ?, address = ? WHERE id = ?";
        $stmt_user = $conn->prepare($sql_user);
        $stmt_user->execute([
            $_POST['full_name'], $email, $_POST['phone'], $password, $_POST['address'], $user_id
        ]);
    } else {
        $sql_user = "UPDATE users SET full_name = ?, email = ?, phone = ?, address = ? WHERE id = ?";
        $stmt_user = $conn->prepare($sql_user);
        $stmt_user->execute([
            $_POST['full_name'], $email, $_POST['phone'], $_POST['address'], $user_id
        ]);
    }

    // --- [3. تحديث جدول doctors] ---
    
    // استلام القيم الجديدة (الأونلاين)
    $is_online_service = $_POST['is_online_service'] ?? 0;
    $is_available_now  = $_POST['is_available_now'] ?? 0;

    // تجهيز الحقول المشتركة مع إضافة الحقلين الجديدين
    $doctor_fields = [
        $_POST['bio'], 
        $_POST['bio_en'], 
        $_POST['experience_years'], 
        $_POST['working_days_ar'], 
        $_POST['working_days_en'], 
        $_POST['working_hours_ar'], 
        $_POST['working_hours_en'], 
        $_POST['patient_duration'], 
        $_POST['consultation_fee'], 
        $_POST['daily_patient_limit'], 
        $_POST['latitude'], 
        $_POST['longitude'],
        $is_online_service, // الحقل الجديد 1
        $is_available_now   // الحقل الجديد 2
    ];

    if ($profile_image_path) {
        // تحديث مع الصورة الجديدة
        $sql_doctor = "UPDATE doctors SET bio = ?, bio_en = ?, experience_years = ?, working_days_ar = ?, 
                       working_days_en = ?, working_hours_ar = ?, working_hours_en = ?, patient_duration = ?, 
                       consultation_fee = ?, daily_patient_limit = ?, latitude = ?, longitude = ?, 
                       is_online_service = ?, is_available_now = ?, profile_image = ? 
                       WHERE user_id = ?";
        $doctor_fields[] = $profile_image_path; 
        $doctor_fields[] = $user_id;           
    } else {
        // تحديث بدون تغيير الصورة
        $sql_doctor = "UPDATE doctors SET bio = ?, bio_en = ?, experience_years = ?, working_days_ar = ?, 
                       working_days_en = ?, working_hours_ar = ?, working_hours_en = ?, patient_duration = ?, 
                       consultation_fee = ?, daily_patient_limit = ?, latitude = ?, longitude = ?,
                       is_online_service = ?, is_available_now = ?
                       WHERE user_id = ?";
        $doctor_fields[] = $user_id;           
    }

    $stmt_doctor = $conn->prepare($sql_doctor);
    $stmt_doctor->execute($doctor_fields);

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

} catch (Exception $e) {
    if (isset($conn) && $conn->inTransaction()) { $conn->rollBack(); }
    echo json_encode(["status" => "error", "message" => "خطأ في السيرفر: " . $e->getMessage()]);
}
?>