<?php

require_once __DIR__ . '/../../core/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    json_response(false, 'Invalid request method.', [], 405);
}

$user = authenticate($pdo);

if (!in_array($user['role'], ['sp_admin', 'artisan'], true)) {
    json_response(false, 'Access denied. SP role required.', [], 403);
}

$sp_company_id = (int)$user['company_id'];
$rsp_id        = (int)$user['rsp_id'];

if (!$sp_company_id) {
    json_response(false, 'Service provider not linked.', [], 403);
}

/* ----------------------------------------------------------
   Load Service Profile (Scoped)
---------------------------------------------------------- */

$stmt = $pdo->prepare("
    SELECT base_lat, base_lng, rsp_id
    FROM service_profiles
    WHERE company_id = ?
    LIMIT 1
");

$stmt->execute([$sp_company_id]);
$profile = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$profile) {
    json_response(false, 'Service profile not configured.', [], 403);
}

/* Defensive RSP validation */

if ((int)$profile['rsp_id'] !== $rsp_id) {
    json_response(false, 'RSP mismatch.', [], 403);
}

$base_lat = (float)$profile['base_lat'];
$base_lng = (float)$profile['base_lng'];

/* ----------------------------------------------------------
   Load Allowed Divisions
---------------------------------------------------------- */

$stmt = $pdo->prepare("
    SELECT division
    FROM service_company_divisions
    WHERE company_id = ?
");

$stmt->execute([$sp_company_id]);
$divisions = $stmt->fetchAll(PDO::FETCH_COLUMN);

if (!$divisions) {
    json_response(true, 'No divisions configured.', [
        'count' => 0,
        'jobs'  => []
    ]);
}

/* ----------------------------------------------------------
   Available Jobs Query
---------------------------------------------------------- */

$placeholders = implode(',', array_fill(0, count($divisions), '?'));

$sql = "
SELECT
    b.id,
    b.division_required,
    b.description,
    b.lat,
    b.lng,
    b.broadcast_started_at,
    b.broadcast_cycle,
    b.broadcast_radius_km,

    (
        6371 * acos(
            cos(radians(?))
            * cos(radians(b.lat))
            * cos(radians(b.lng) - radians(?))
            + sin(radians(?))
            * sin(radians(b.lat))
        )
    ) AS distance_km

FROM breakdowns b
JOIN companies c ON c.id = b.fleet_company_id

WHERE b.status = 'broadcasting'
  AND b.accepted_company_id IS NULL
  AND NOW() < b.broadcast_expires_at
  AND c.rsp_id = ?
  AND b.division_required IN ($placeholders)

HAVING distance_km <= b.broadcast_radius_km

ORDER BY distance_km ASC
LIMIT 100
";

$params = [
    $base_lat,
    $base_lng,
    $base_lat,
    $rsp_id
];

$params = array_merge($params, $divisions);

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

json_response(true, 'Available jobs fetched.', [
    'count' => count($jobs),
    'jobs'  => $jobs
]);