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

require_once "../../dbcon.php";

$method = $_SERVER["REQUEST_METHOD"];

function sanitize($data) {
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

switch ($method) {
    case "GET":
        // --- Auto-Migration: Ensure agent_id exists ---
        $check_col = mysqli_query($conn, "SHOW COLUMNS FROM users LIKE 'agent_id'");
        if (mysqli_num_rows($check_col) == 0) {
            mysqli_query($conn, "ALTER TABLE users ADD COLUMN agent_id INT DEFAULT NULL AFTER otp_expires_at");
            mysqli_query($conn, "ALTER TABLE users ADD CONSTRAINT fk_user_agent FOREIGN KEY (agent_id) REFERENCES users(id) ON DELETE SET NULL");
        }

        if (isset($_GET['get_agents'])) {
            // Get all users who are agents (Case-insensitive role check)
            $query = "SELECT u.id, u.full_name, u.email FROM users u 
                      JOIN roles r ON u.role_id = r.id 
                      WHERE LOWER(r.role_name) = 'agent'";
            $res = mysqli_query($conn, $query);
            $agents = [];
            while ($row = mysqli_fetch_assoc($res)) $agents[] = $row;
            echo json_encode(["status" => "success", "data" => $agents]);
        } else {
            // Get users (optionally filtered by agent)
            $agent_id = isset($_GET['agent_id']) ? intval($_GET['agent_id']) : null;
            $query = "SELECT u.id, u.full_name, u.email, u.phone, u.country, u.status, u.agent_id, a.full_name as agent_name 
                      FROM users u 
                      LEFT JOIN users a ON u.agent_id = a.id
                      JOIN roles r ON u.role_id = r.id
                      WHERE LOWER(r.role_name) = 'user'";
            
            if ($agent_id) {
                $query .= " AND u.agent_id = $agent_id";
            }
            
            $res = mysqli_query($conn, $query);
            $users = [];
            while ($row = mysqli_fetch_assoc($res)) $users[] = $row;
            echo json_encode(["status" => "success", "data" => $users]);
        }
        break;

    case "POST":
        // This could be used for assigning agent to user
        $data = json_decode(file_get_contents("php://input"), true);
        $user_id = intval($data['user_id'] ?? 0);
        $agent_id = isset($data['agent_id']) ? intval($data['agent_id']) : null;

        if ($user_id > 0) {
            $agent_val = $agent_id === null ? "NULL" : $agent_id;
            $query = "UPDATE users SET agent_id = $agent_val WHERE id = $user_id";
            if (mysqli_query($conn, $query)) {
                echo json_encode(["status" => "success", "message" => "Agent assigned successfully"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Update failed: " . mysqli_error($conn)]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "User ID required"]);
        }
        break;

    case "OPTIONS":
        http_response_code(200);
        break;
}

mysqli_close($conn);
?>
