<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8");

include_once 'db_connect.php'; 

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

if (!$user_id) {
    echo json_encode(["status" => "error", "message" => "المعرف user_id مفقود"]);
    exit;
}

try {
    $full_name = $_POST['full_name'] ?? '';
    $email     = $_POST['email'] ?? '';
    $phone     = $_POST['phone'] ?? '';
    $city      = $_POST['city'] ?? '';
    $address   = $_POST['address'] ?? '';
    $password  = $_POST['password'] ?? '';

    $image_update_sql = "";
    $params = [
        ':full_name' => $full_name,
        ':email'     => $email,
        ':phone'     => $phone,
        ':city'      => $city,
        ':address'   => $address,
        ':id'        => $user_id
    ];

    // --- إعداد المسارات ---
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
        
        $folder_path = "uploads/representatives/"; 
        
        // التأكد من وجود المجلد على السيرفر
        if (!file_exists($folder_path)) {
            mkdir($folder_path, 0777, true);
        }

        $file_extension = pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION);
        $file_name = "rep_" . $user_id . "_" . time() . "." . $file_extension;
        $full_save_path = $folder_path . $file_name; // المسار الكامل (uploads/representatives/filename.jpg)

        if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $full_save_path)) {
            // تحديث الاستعلام لحفظ المسار الكامل في قاعدة البيانات
            $image_update_sql = ", profile_image = :profile_image";
            $params[':profile_image'] = $full_save_path; 
        }
    }

    // تحديث كلمة المرور
    $pass_update_sql = "";
    if (!empty($password)) {
        $pass_update_sql = ", password = :password";
        $params[':password'] = password_hash($password, PASSWORD_DEFAULT);
    }

    $query = "UPDATE users SET 
                full_name = :full_name, 
                email = :email, 
                phone = :phone, 
                city = :city, 
                address = :address 
                $image_update_sql 
                $pass_update_sql 
              WHERE id = :id AND role_id = 10";

    $stmt = $conn->prepare($query);
    
    if ($stmt->execute($params)) {
        echo json_encode(["status" => "success", "message" => "تم تحديث البيانات بنجاح"]);
    } else {
        echo json_encode(["status" => "error", "message" => "فشل التحديث"]);
    }

} catch (PDOException $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>