<?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":
        $agent_id = isset($_GET['agent_id']) ? intval($_GET['agent_id']) : null;
        $query = "SELECT l.id, l.full_name as name, l.email, l.phone, l.message as interest, l.source, l.status, l.agent_id, l.created_at, a.full_name as agent_name 
                  FROM site_inquiries l 
                  LEFT JOIN users a ON l.agent_id = a.id";
        
        if ($agent_id) {
            $query .= " WHERE l.agent_id = $agent_id";
        }
        $query .= " ORDER BY l.created_at DESC";
        
        $res = mysqli_query($conn, $query);
        $leads = [];
        while ($row = mysqli_fetch_assoc($res)) $leads[] = $row;
        echo json_encode(["status" => "success", "data" => $leads]);
        break;

    case "POST":
        // This can be used for updating lead or assigning agent to lead
        $data = json_decode(file_get_contents("php://input"), true);
        $lead_id = intval($data['lead_id'] ?? $data['id'] ?? 0);
        $agent_id = isset($data['agent_id']) ? intval($data['agent_id']) : null;
        $status = sanitize($data['status'] ?? '');

        if ($lead_id > 0) {
            $updates = [];
            if ($agent_id !== null || isset($data['agent_id'])) {
                $agent_val = ($agent_id === null || $agent_id === 0) ? "NULL" : $agent_id;
                $updates[] = "agent_id = $agent_val";
            }
            if ($status) {
                $updates[] = "status = '$status'";
            }

            if (empty($updates)) {
                echo json_encode(["status" => "error", "message" => "Nothing to update"]);
                break;
            }

            $query = "UPDATE site_inquiries SET " . implode(", ", $updates) . " WHERE id = $lead_id";
            if (mysqli_query($conn, $query)) {
                echo json_encode(["status" => "success", "message" => "Lead updated successfully"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Update failed: " . mysqli_error($conn)]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Lead ID required"]);
        }
        break;

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

mysqli_close($conn);
?>
