<?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
---------------------------------------------------------- */

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

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

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 = [];

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

if ($status_filter) {
    $where[] = "b.status = ?";
    $params[] = $status_filter;
}

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 = '';
if ($where) {
    $where_sql = "WHERE " . implode(" AND ", $where);
}

/* ----------------------------------------------------------
   JOB LIST
---------------------------------------------------------- */

$sql = "
SELECT
    b.id,
    b.status,
    b.issue_division,
    b.description,
    b.po_number,
    b.created_at,
    b.started_at,
    b.arrived_at,
    b.completed_at,
    b.travel_distance_km,
    b.billable_distance_km,
    f.company_name AS fleet_name,
    s.company_name AS sp_name
FROM breakdowns b
JOIN companies f ON f.id = b.fleet_company_id
LEFT JOIN companies s ON s.id = b.accepted_company_id
{$where_sql}
ORDER BY b.created_at DESC
LIMIT ?
";

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

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

/* ----------------------------------------------------------
   SUMMARY
---------------------------------------------------------- */

$summary_sql = "
SELECT
    COUNT(*) AS total_jobs,
    COALESCE(SUM(b.travel_distance_km), 0) AS total_travel,
    COALESCE(SUM(b.billable_distance_km), 0) AS total_billable
FROM breakdowns b
JOIN companies f ON f.id = b.fleet_company_id
{$where_sql}
";

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

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

json_response(true, 'Admin overview fetched.', [
    'summary' => [
        'total_jobs'        => (int)$summary['total_jobs'],
        'total_travel_km'   => (float)$summary['total_travel'],
        'total_billable_km' => (float)$summary['total_billable']
    ],
    'count' => count($jobs),
    'jobs'  => $jobs
]);