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

$data = json_decode(file_get_contents("php://input"), true);

$id        = intval($data['id'] ?? 0);
$username  = trim($data['username'] ?? '');
$mobile    = trim($data['mobile'] ?? '');
$email     = trim($data['email'] ?? '');
$user_type = trim($data['user_type'] ?? '');
$password  = trim($data['password'] ?? '');
$status    = trim($data['status'] ?? 'نشط');
$notes     = trim($data['notes'] ?? '');

if ($id === 0 || $username === "" || $mobile === "" || $email === "" || $user_type === "") {
    echo json_encode(["status" => "error", "message" => "⚠️ كل الحقول مطلوبة"]);
    exit;
}

if ($password !== "") {
    // لو تم إدخال باسورد جديد
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $sql = "UPDATE USEUSERSMH 
            SET username=?, mobile=?, email=?, user_type=?, password=?, status=?, notes=? 
            WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssssssi", $username, $mobile, $email, $user_type, $hashed_password, $status, $notes, $id);
} else {
    // بدون تحديث الباسورد
    $sql = "UPDATE USEUSERSMH 
            SET username=?, mobile=?, email=?, user_type=?, status=?, notes=? 
            WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssssssi", $username, $mobile, $email, $user_type, $status, $notes, $id);
}

if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "✅ تم تعديل بيانات المستخدم"]);
} else {
    echo json_encode(["status" => "error", "message" => "❌ خطأ: " . $stmt->error]);
}

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