<?php

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

/* ----------------------------------------------------------
   DB CONNECTION FIRST
---------------------------------------------------------- */

$pdo = get_db_connection();

/* ----------------------------------------------------------
   AUTH
---------------------------------------------------------- */

$auth_user = require_auth($pdo);

/* ----------------------------------------------------------
   PLATFORM ACCESS
---------------------------------------------------------- */

platform_enabled($auth_user['id'], 'assist');

/* ----------------------------------------------------------
   ROLE CHECK
---------------------------------------------------------- */

$user_role = get_assist_role($auth_user['id']);

if (!in_array($user_role, ['sp_admin', 'artisan'])) {
    json_response(false, 'Access denied: Invalid Assist role.');
}

$pdo = get_db_connection();

// Get SP company
$stmt = $pdo->prepare("
    SELECT c.id, c.rsp_id
    FROM companies c
    JOIN dpa_service_profiles sp ON sp.company_id = c.id
    WHERE c.owner_user_id = ?
    LIMIT 1
");
$stmt->execute([$auth_user['id']]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    json_response(false, 'Service Provider profile not found.');
}

$sp_company_id = $company['id'];
$sp_rsp_id     = $company['rsp_id'];

// Get SP geo profile
$stmt = $pdo->prepare("
    SELECT base_lat, base_lng, coverage_radius_km
    FROM dpa_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.');
}

$base_lat = $profile['base_lat'];
$base_lng = $profile['base_lng'];

// ---- Dynamic Tier Expansion ----

$stmt = $pdo->query("
    SELECT id, broadcast_started_at, current_radius_km
    FROM dpa_breakdowns
    WHERE status = 'broadcasting'
      AND accepted_company_id IS NULL
      AND broadcast_started_at IS NOT NULL
");

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

foreach ($breakdowns as $b) {

    $elapsed = time() - strtotime($b['broadcast_started_at']);
    $tier = floor($elapsed / 300) + 1;
    if ($tier < 1) $tier = 1;

    $new_radius = 25 * $tier;

    if ($new_radius > $b['current_radius_km']) {

        $update = $pdo->prepare("
            UPDATE dpa_breakdowns
            SET current_radius_km = ?, tier_level = ?
            WHERE id = ?
        ");

        $update->execute([$new_radius, $tier, $b['id']]);
    }
}

// ---- Fetch Available Jobs ----

$sql = "
SELECT
    b.id,
    b.description,
    b.latitude,
    b.longitude,
    b.current_radius_km,
    b.tier_level,
    b.created_at,

    ( 6371 * acos(
        cos(radians(:base_lat))
        * cos(radians(b.latitude))
        * cos(radians(b.longitude) - radians(:base_lng))
        + sin(radians(:base_lat))
        * sin(radians(b.latitude))
    )) AS distance

FROM dpa_breakdowns b

JOIN companies fleet_company
    ON fleet_company.id = b.fleet_id

WHERE b.status = 'broadcasting'
  AND b.accepted_company_id IS NULL
  AND fleet_company.rsp_id = :rsp_id

  AND b.issue_division IN (
        SELECT division_id
        FROM dpa_service_company_divisions
        WHERE company_id = :company_id
  )

HAVING distance <= b.current_radius_km

ORDER BY distance ASC
";

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

$stmt->execute([
    ':base_lat'    => $base_lat,
    ':base_lng'    => $base_lng,
    ':rsp_id'      => $sp_rsp_id,
    ':company_id'  => $sp_company_id
]);

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

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