<?php
/**
 * Cincinnati Fire Department Portal - Constants & Shift Rotation Engine
 */

require_once __DIR__ . '/db.php';

// App constants
define('APP_NAME', env('APP_NAME', 'Cincinnati Fire Portal'));
define('APP_URL', env('APP_URL', 'https://cincinnatifire.ai'));
define('APP_VERSION', '1.0.0');
define('PORTAL_SESSION_HOURS', 8);
define('PORTAL_UPLOAD_MAX', 10485760); // 10MB
define('PORTAL_UPLOAD_DIR', __DIR__ . '/../uploads');

// Allowed upload types
define('ALLOWED_DOC_TYPES', [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'image/jpeg',
    'image/png',
    'image/gif'
]);

// Location
define('CITY_LAT', 39.1031);
define('CITY_LNG', -84.5120);
define('CITY_NAME', 'Cincinnati');
define('STATE_CODE', 'OH');

// Refresh intervals (milliseconds)
define('WEATHER_REFRESH', 600000);     // 10 minutes
define('NEWS_REFRESH', 900000);        // 15 minutes
define('INCIDENT_REFRESH', 15000);     // 15 seconds
define('SHIFT_REFRESH', 3600000);      // 1 hour

// API keys (from .env)
define('OPENWEATHER_API_KEY', env('OPENWEATHER_API_KEY', ''));
define('GOOGLE_MAPS_API_KEY', env('GOOGLE_MAPS_API_KEY', ''));
define('HERE_API_KEY', env('HERE_API_KEY', ''));
define('OHGO_API_KEY', env('OHGO_API_KEY', ''));
define('BROADCASTIFY_PLAYER_ID', env('BROADCASTIFY_PLAYER_ID', '5184'));
define('TEAMUP_CALENDAR_KEY', env('TEAMUP_CALENDAR_KEY', ''));
define('ACTIVE911_WEBHOOK_URL', env('ACTIVE911_WEBHOOK_URL', ''));

// Department structure
define('ROLES', [
    'admin'           => ['label' => 'Administrator', 'level' => 9],
    'chief'           => ['label' => 'Fire Chief', 'level' => 8],
    'asst_chief'      => ['label' => 'Assistant Chief', 'level' => 7],
    'district_chief'  => ['label' => 'District Chief', 'level' => 6],
    'captain'         => ['label' => 'Captain', 'level' => 5],
    'lieutenant'      => ['label' => 'Lieutenant', 'level' => 4],
    'firefighter'     => ['label' => 'Firefighter', 'level' => 3],
    'hr_finance'      => ['label' => 'HR/Finance', 'level' => 2],
    'guest'           => ['label' => 'Guest', 'level' => 1],
]);

// Shift rotation configuration
define('SHIFT_UNITS', [
    3 => ['label' => 'A Shift', 'name' => 'Red',   'color' => '#DC2626', 'unit' => 'Unit 3'],
    1 => ['label' => 'B Shift', 'name' => 'Green', 'color' => '#16A34A', 'unit' => 'Unit 1'],
    2 => ['label' => 'C Shift', 'name' => 'Blue',  'color' => '#2563EB', 'unit' => 'Unit 2'],
]);

// Rotation order: Unit 3 → Unit 1 → Unit 2 → repeat
define('SHIFT_ROTATION', [3, 1, 2]);

/**
 * Calculate which shift/unit is on duty for a given date.
 *
 * Rotation: 3-day cycle. Anchor: Unit 3 on 2026-03-26.
 * Sequence: Unit 3 (day 0) → Unit 1 (day 1) → Unit 2 (day 2) → Unit 3 (day 3) → ...
 *
 * @param string|null $date  Date string (Y-m-d) or null for today
 * @return array  ['unit_num', 'unit', 'label', 'name', 'color']
 */
function getShiftForDate($date = null) {
    $anchorDate = env('SHIFT_ANCHOR_DATE', '2026-03-26');
    $target = $date ? new DateTime($date) : new DateTime();
    $anchor = new DateTime($anchorDate);

    $diff = (int)$anchor->diff($target)->format('%r%a');
    $position = (($diff % 3) + 3) % 3; // Handle negative for past dates

    $rotation = SHIFT_ROTATION;
    $unitNum = $rotation[$position];
    $info = SHIFT_UNITS[$unitNum];

    return [
        'unit_num' => $unitNum,
        'unit'     => $info['unit'],
        'label'    => $info['label'],
        'name'     => $info['name'],
        'color'    => $info['color'],
    ];
}

/**
 * Get the current shift day boundaries (0700 to 0700).
 * A "shift day" starts at 07:00 and ends at 07:00 the next calendar day.
 * Before 07:00, we're still on the previous shift day.
 *
 * @return array ['start' => 'Y-m-d H:i:s', 'end' => 'Y-m-d H:i:s', 'shift_date' => 'Y-m-d', 'shift' => array]
 */
function getCurrentShiftBounds() {
    date_default_timezone_set('America/New_York');
    $now = new DateTime();
    $hour = (int)$now->format('H');

    if ($hour < 7) {
        // Before 0700 — still on yesterday's shift
        $shiftDate = (clone $now)->modify('-1 day')->format('Y-m-d');
    } else {
        $shiftDate = $now->format('Y-m-d');
    }

    $start = $shiftDate . ' 07:00:00';
    $end = date('Y-m-d', strtotime($shiftDate . ' +1 day')) . ' 07:00:00';
    $shift = getShiftForDate($shiftDate);

    return [
        'start' => $start,
        'end' => $end,
        'shift_date' => $shiftDate,
        'shift' => $shift,
    ];
}

/**
 * Get the previous shift day boundaries.
 *
 * @return array Same format as getCurrentShiftBounds
 */
function getPreviousShiftBounds() {
    date_default_timezone_set('America/New_York');
    $current = getCurrentShiftBounds();
    $prevDate = date('Y-m-d', strtotime($current['shift_date'] . ' -1 day'));
    $start = $prevDate . ' 07:00:00';
    $end = $current['start'];
    $shift = getShiftForDate($prevDate);

    return [
        'start' => $start,
        'end' => $end,
        'shift_date' => $prevDate,
        'shift' => $shift,
    ];
}

/**
 * Get shifts for today, tomorrow, and day-after-tomorrow.
 *
 * @return array  Array of 3 shift info arrays with 'date' key added
 */
function getUpcomingShifts() {
    $shifts = [];
    for ($i = 0; $i < 3; $i++) {
        $date = (new DateTime())->modify("+{$i} days")->format('Y-m-d');
        $shift = getShiftForDate($date);
        $shift['date'] = $date;
        $shift['day_label'] = $i === 0 ? 'Today' : ($i === 1 ? 'Tomorrow' : date('D', strtotime($date)));
        $shifts[] = $shift;
    }
    return $shifts;
}
