<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

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

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'escalations', 'view', $pdo);

$where = [];
$params = [];

/* TENANT ISOLATION */
if (!empty($user['rsp_id'])) {
    $where[] = "c.rsp_id = ?";
    $params[] = (int)$user['rsp_id'];
}

$where_sql = '';
if ($where) {
    $where_sql = " AND " . implode(" AND ", $where);
}

/* COMBINED QUERY */
$sql = "
SELECT 
    b.id,
    b.status,
    b.tier_level,
    TIMESTAMPDIFF(MINUTE, b.broadcast_started_at, NOW()) AS broadcast_minutes,
    TIMESTAMPDIFF(MINUTE, b.allocated_at, NOW()) AS allocated_minutes,
    TIMESTAMPDIFF(MINUTE, b.started_at, NOW()) AS enroute_minutes,
    TIMESTAMPDIFF(MINUTE, b.arrived_at, NOW()) AS repair_minutes
FROM breakdowns b
JOIN companies c ON c.id = b.fleet_company_id
WHERE b.status IN ('broadcasting','allocated','enroute','in_progress')
{$where_sql}
LIMIT 1000
";

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

$alerts = [];

foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {

    if ($row['status'] === 'broadcasting' && $row['broadcast_minutes'] > 15) {
        $alerts[] = [
            'breakdown_id' => $row['id'],
            'type' => 'Broadcasting Timeout',
            'status' => $row['status']
        ];
    }

    if ($row['status'] === 'allocated' && $row['allocated_minutes'] > 10) {
        $alerts[] = [
            'breakdown_id' => $row['id'],
            'type' => 'Dispatch Delay',
            'status' => $row['status']
        ];
    }

    if ($row['status'] === 'enroute') {
        $tier_limit = (int)$row['tier_level'] * 30;
        if ($row['enroute_minutes'] > $tier_limit) {
            $alerts[] = [
                'breakdown_id' => $row['id'],
                'type' => 'Travel SLA Exceeded',
                'status' => $row['status']
            ];
        }
    }

    if ($row['status'] === 'in_progress' && $row['repair_minutes'] > 120) {
        $alerts[] = [
            'breakdown_id' => $row['id'],
            'type' => 'Repair Duration Exceeded',
            'status' => $row['status']
        ];
    }
}

json_response(true, 'Escalations fetched.', [
    'count' => count($alerts),
    'alerts' => $alerts
]);