<?php
// Shared utility functions

/**
 * Generates <option> elements for time-spent dropdown (15m increments up to 8h)
 */
function generateTimeOptions($selected = null) {
    $nothingSelected = ($selected === null || $selected === '');
    $html = "<option value='" . ($nothingSelected ? "' selected" : "'") . "></option>";
    $sel0 = (!$nothingSelected && ($selected === 0 || $selected === '0')) ? 'selected' : '';
    $html .= "<option value='0' $sel0>0</option>";
    for ($i = 15; $i <= 480; $i += 15) {
        $hours   = floor($i / 60);
        $minutes = $i % 60;
        $label   = ($hours > 0 ? "{$hours}h " : "") . ($minutes > 0 ? "{$minutes}m" : "");
        $sel     = (!$nothingSelected && $selected == $i) ? 'selected' : '';
        $html   .= "<option value='$i' $sel>$label</option>";
    }
    return $html;
}

function getPtoBalance($pdo, $user_id, $year) {
    $stmt = $pdo->prepare("SELECT allotted_hours, manual_adjustment FROM pto_balance WHERE user_id = ? AND year = ?");
    $stmt->execute([$user_id, $year]);
    $row = $stmt->fetch();
    $allotted = (float)($row['allotted_hours'] ?? 0);
    $manual   = (float)($row['manual_adjustment'] ?? 0);

    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(te.hours), 0)
        FROM time_entries te
        JOIN accounts a ON a.id = te.account_id
        WHERE a.category = 'PTO'
          AND te.timesheet_id IN (SELECT id FROM timesheets WHERE user_id = ?)
          AND YEAR(te.entry_date) = ?
    ");
    $stmt->execute([$user_id, $year]);
    $tracked = (float)$stmt->fetchColumn();
    $used = $tracked + $manual;

    return [
        'allotted'  => $allotted,
        'tracked'   => $tracked,
        'manual'    => $manual,
        'used'      => $used,
        'remaining' => $allotted - $used,
    ];
}
