<?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, 'analytics', 'view', $pdo);

/* ----------------------------------------------------------
   FILTERS
---------------------------------------------------------- */

$date_from = $_GET['date_from'] ?? null;
$date_to   = $_GET['date_to'] ?? null;
$limit     = isset($_GET['limit']) ? (int)$_GET['limit'] : 500;

if ($limit <= 0 || $limit > 1000) {
    $limit = 500;
}

if ($date_from && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from)) {
    json_response(false, 'Invalid date_from format.', [], 400);
}

if ($date_to && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to)) {
    json_response(false, 'Invalid date_to format.', [], 400);
}

/* ----------------------------------------------------------
   WHERE BUILDER
---------------------------------------------------------- */

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

$where[] = "b.completed_at IS NOT NULL";
$where[] = "b.accepted_company_id IS NOT NULL";

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

if ($date_from) {
    $where[] = "b.created_at >= ?";
    $params[] = $date_from . " 00:00:00";
}

if ($date_to) {
    $where[] = "b.created_at <= ?";
    $params[] = $date_to . " 23:59:59";
}

$where_sql = 'WHERE ' . implode(' AND ', $where);

/* ----------------------------------------------------------
   RANKING QUERY
---------------------------------------------------------- */

$sql = "
SELECT
    c.id AS sp_id,
    c.company_name AS sp_name,
    COUNT(b.id) AS completed_jobs,
    ROUND(AVG(TIMESTAMPDIFF(SECOND, b.broadcast_started_at, b.allocated_at)/60), 2) AS avg_time_to_accept_min,
    ROUND(AVG(TIMESTAMPDIFF(SECOND, b.started_at, b.arrived_at)/60), 2) AS avg_travel_time_min,
    ROUND(AVG(TIMESTAMPDIFF(SECOND, b.arrived_at, b.completed_at)/60), 2) AS avg_repair_time_min,
    ROUND(AVG(TIMESTAMPDIFF(SECOND, b.created_at, b.completed_at)/60), 2) AS avg_total_duration_min
FROM breakdowns b
JOIN companies c ON c.id = b.accepted_company_id
JOIN companies f ON f.id = b.fleet_company_id
{$where_sql}
GROUP BY c.id, c.company_name
ORDER BY avg_time_to_accept_min ASC, avg_total_duration_min ASC
LIMIT ?
";

$params_with_limit = array_merge($params, [$limit]);

$stmt = $pdo->prepare($sql);
$stmt->execute($params_with_limit);
$rankings = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ----------------------------------------------------------
   ASSIGN RANK
---------------------------------------------------------- */

$rank = 1;
foreach ($rankings as &$entry) {
    $entry['rank'] = $rank++;
    $entry['completed_jobs'] = (int)$entry['completed_jobs'];
    $entry['avg_time_to_accept_min'] = (float)$entry['avg_time_to_accept_min'];
    $entry['avg_travel_time_min'] = (float)$entry['avg_travel_time_min'];
    $entry['avg_repair_time_min'] = (float)$entry['avg_repair_time_min'];
    $entry['avg_total_duration_min'] = (float)$entry['avg_total_duration_min'];
}

json_response(true, 'SP rankings generated.', [
    'total_sp' => count($rankings),
    'rankings' => $rankings
]);