<?php
declare(strict_types=1);

require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/api_security.php';

header('Content-Type: application/json');

requireApiLogin();

$action = $_GET['action'] ?? '';

if (!isAdmin() && !can('driver.off_duty.view')) {
    respond(['status' => 'error', 'message' => 'Unauthorized']);
}

try {
    switch ($action) {
        case 'overview': handleOverview($pdo); break;
        default: respond(['status' => 'error', 'message' => 'Unknown action']);
    }
} catch (Exception $e) {
    respond(['status' => 'error', 'message' => $e->getMessage()]);
}

function respond(array $payload): void { apiRespond($payload); }

function handleOverview(PDO $pdo): void
{
    $month = $_GET['month'] ?? date('Y-m');
    $driverId = (int)($_GET['driver_id'] ?? 0);

    $where = 'd.deleted_at IS NULL';
    $params = [];

    if ($driverId > 0) {
        $where .= ' AND d.id = :driver_id';
        $params['driver_id'] = $driverId;
    }

    $stmt = $pdo->prepare("
        SELECT d.id AS driver_id, d.full_name AS driver_name,
               COALESCE(o.month_year, :month) AS month_year,
               COALESCE(o.days_taken, 0) AS days_taken
        FROM drivers d
        LEFT JOIN (
            SELECT driver_id, month_year, COUNT(*) AS days_taken
            FROM driver_off_duty
            WHERE month_year = :month2 AND deleted_at IS NULL
            GROUP BY driver_id, month_year
        ) o ON o.driver_id = d.id
        WHERE {$where}
        ORDER BY d.full_name ASC
    ");
    $stmt->execute(array_merge($params, ['month' => $month, 'month2' => $month]));
    $rows = $stmt->fetchAll();

    respond(['status' => 'success', 'data' => $rows]);
}
