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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id   = $_POST['user_id'];
    $full_name = $_POST['full_name'];
    $email     = $_POST['email'];
    $phone     = $_POST['phone'];
    $city      = $_POST['city'];
    $address   = $_POST['address'];
    $password  = $_POST['password'];

    try {
        // 1. معالجة الصورة إذا تم رفع صورة جديدة
        $image_sql = "";
        if (isset($_FILES['profile_image'])) {
            $target_dir = "uploads/profiles/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            
            $file_extension = pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION);
            $file_name = "admin_" . $user_id . "_" . time() . "." . $file_extension;
            $target_file = $target_dir . $file_name;

            if (move_uploaded_file($_FILES["profile_image"]["tmp_name"], $target_file)) {
                $image_path = "uploads/profiles/" . $file_name;
                $image_sql = ", profile_image = '$image_path'";
            }
        }

        // 2. معالجة كلمة المرور إذا لم تكن فارغة
        $password_sql = "";
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $password_sql = ", password = '$hashed_password'";
        }

        // 3. التحديث في جدول users (الجدول الأساسي للأدمن)
        $sql = "UPDATE users SET 
                full_name = ?, 
                email = ?, 
                phone = ?, 
                city = ?, 
                address = ? 
                $image_sql 
                $password_sql 
                WHERE id = ?";

        $stmt = $conn->prepare($sql);
        $success = $stmt->execute([$full_name, $email, $phone, $city, $address, $user_id]);

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

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