<?php

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

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

$user = authenticate($pdo);

if (!in_array($user['role'], ['sp_admin', 'artisan'], true)) {
    json_response(false, 'Access denied. SP role required.', [], 403);
}

$sp_company_id = (int)$user['company_id'];
$rsp_id        = (int)$user['rsp_id'];

if (!$sp_company_id) {
    json_response(false, 'Service provider not linked.', [], 403);
}

/* ----------------------------------------------------------
   Filters
---------------------------------------------------------- */

$include_completed = isset($_GET['include_completed']) && $_GET['include_completed'] === '1';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;

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

/* ----------------------------------------------------------
   Job Query
---------------------------------------------------------- */

$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
FROM breakdowns b
JOIN companies f ON f.id = b.fleet_company_id
WHERE b.accepted_company_id = ?
  AND f.rsp_id = ?
  AND b.archived_at IS NULL
";

$params = [$sp_company_id, $rsp_id];

if (!$include_completed) {
    $sql .= " AND b.status NOT IN ('completed', 'cancelled')";
}

$sql .= " ORDER BY b.created_at DESC LIMIT {$limit}";

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

/* ----------------------------------------------------------
   Summary Query (Scoped + Safe)
---------------------------------------------------------- */

$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 b.accepted_company_id = ?
  AND f.rsp_id = ?
";

$summary_params = [$sp_company_id, $rsp_id];

if (!$include_completed) {
    $summary_sql .= " AND b.status NOT IN ('completed', 'cancelled', 'archived')";
}

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

json_response(true, 'SP dashboard data fetched.', [
    'summary' => [
        'total_jobs'        => (int)$summary['total_jobs'],
        'total_travel_km'   => (int)$summary['total_travel'],
        'total_billable_km' => (int)$summary['total_billable']
    ],
    'count' => count($jobs),
    'jobs'  => $jobs
]);