<?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'] : 200;

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

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";

/* 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);

/* ----------------------------------------------------------
   PER JOB METRICS
---------------------------------------------------------- */

$metrics_sql = "
SELECT
    b.id AS breakdown_id,
    ROUND(TIMESTAMPDIFF(SECOND, b.broadcast_started_at, b.allocated_at)/60, 2) AS time_to_accept_min,
    ROUND(TIMESTAMPDIFF(SECOND, b.started_at, b.arrived_at)/60, 2) AS travel_time_min,
    ROUND(TIMESTAMPDIFF(SECOND, b.arrived_at, b.completed_at)/60, 2) AS repair_time_min,
    ROUND(TIMESTAMPDIFF(SECOND, b.created_at, b.completed_at)/60, 2) AS total_duration_min
FROM breakdowns b
JOIN companies f ON f.id = b.fleet_company_id
{$where_sql}
ORDER BY b.completed_at DESC
LIMIT ?
";

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

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

/* ----------------------------------------------------------
   AGGREGATE METRICS
---------------------------------------------------------- */

$aggregate_sql = "
SELECT
    COUNT(*) AS jobs_analyzed,
    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 f ON f.id = b.fleet_company_id
{$where_sql}
";

$stmt = $pdo->prepare($aggregate_sql);
$stmt->execute($params);
$averages = $stmt->fetch(PDO::FETCH_ASSOC);

/* ----------------------------------------------------------
   RESPONSE
---------------------------------------------------------- */

json_response(true, 'SLA analytics calculated.', [
    'jobs_analyzed' => (int)$averages['jobs_analyzed'],
    'averages' => [
        'avg_time_to_accept_min' => (float)$averages['avg_time_to_accept_min'],
        'avg_travel_time_min'    => (float)$averages['avg_travel_time_min'],
        'avg_repair_time_min'    => (float)$averages['avg_repair_time_min'],
        'avg_total_duration_min' => (float)$averages['avg_total_duration_min']
    ],
    'job_metrics' => $job_metrics
]);