<?php
// === CORS Headers for React Dev Server ===
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

header("Content-Type: application/json");
include '../../dbcon.php';

// ------------------- GET USERS -------------------
if ($_SERVER['REQUEST_METHOD'] === 'GET' && !isset($_GET['roles'])) {
    $result = mysqli_query($conn, "
    SELECT u.id, u.role_id, r.role_name, u.full_name, u.email, u.phone, u.country, u.status
    FROM users u
    LEFT JOIN roles r ON u.role_id = r.id
");
    $users = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $users[] = $row;
    }
    echo json_encode([
        "status" => "success",
        "users" => $users
    ]);
    exit;
}

// ------------------- GET ROLES -------------------
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['roles'])) {
    $result = mysqli_query($conn, "SELECT id, role_name FROM roles");
    $roles = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $roles[] = $row;
    }
    echo json_encode([
        "status" => "success",
        "roles" => $roles
    ]);
    exit;
}

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

// Default role_id = 2 (user)
$role_id = intval($data['role_id'] ?? 2);
$agent_id = isset($data['agent_id']) && $data['agent_id'] !== "" ? intval($data['agent_id']) : null;
$full_name = mysqli_real_escape_string($conn, $data['full_name'] ?? '');
$email = mysqli_real_escape_string($conn, $data['email'] ?? '');
$phone = mysqli_real_escape_string($conn, $data['phone'] ?? '');
$country = mysqli_real_escape_string($conn, $data['country'] ?? '');
$password = mysqli_real_escape_string($conn, $data['password'] ?? '');

// Validate required fields
if (!$full_name || !$email || !$password) {
    echo json_encode([
        "status" => "error",
        "message" => "Full name, email, and password are required"
    ]);
    exit;
}

// Check if email already exists
$exists = mysqli_query($conn, "SELECT id FROM users WHERE email='$email'");
if (mysqli_num_rows($exists) > 0) {
    echo json_encode([
        "status" => "error",
        "message" => "Email already registered"
    ]);
    exit;
}

// Insert new user
$hashed = password_hash($password, PASSWORD_BCRYPT);

// Validate role_id exists in roles table
$role_check = mysqli_query($conn, "SELECT id FROM roles WHERE id='$role_id'");
if (mysqli_num_rows($role_check) === 0) {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid role selected"
    ]);
    exit;
}

$agent_val = $agent_id === null ? "NULL" : $agent_id;
$query = "INSERT INTO users (role_id, agent_id, full_name, email, phone, country, password, status) 
          VALUES ('$role_id', $agent_val, '$full_name', '$email', '$phone', '$country', '$hashed', 'inactive')";

if (mysqli_query($conn, $query)) {
    echo json_encode([
        "status" => "success",
        "message" => "Registration successful",
        "user" => [
            "id" => mysqli_insert_id($conn),
            "full_name" => $full_name,
            "email" => $email,
            "role_id" => (string)$role_id,
            "agent_id" => $agent_id
        ]
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Registration failed: " . mysqli_error($conn)
    ]);
}
