<?php
session_start();
require_once 'functions.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

$selectedMonth = isset($_GET['month']) ? intval($_GET['month']) : date('m');
$selectedYear = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

$allRecords = getRecords();
$filteredRecords = filterRecordsByMonthYear($allRecords, $selectedMonth, $selectedYear);

// Group by airline and date
$dailyHours = [];

foreach ($filteredRecords as $rec) {
    $airline = $rec['airline'];
    $date = date('Y-m-d', strtotime($rec['arrival_datetime']));
    $hours = getTotalEngineerHoursForRecord($rec);
    
    if (!isset($dailyHours[$airline])) {
        $dailyHours[$airline] = [];
    }
    if (!isset($dailyHours[$airline][$date])) {
        $dailyHours[$airline][$date] = 0;
    }
    $dailyHours[$airline][$date] += $hours;
}

// Handle Excel export
if (isset($_GET['export_excel']) && $_GET['export_excel'] == '1') {
    exportDailyHoursToExcel($dailyHours, $selectedMonth, $selectedYear);
    exit;
}

$monthNames = [
    1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June',
    7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Daily Engineer Hours Report</title>
    <style>
        *{box-sizing:border-box}body{font-family:'Segoe UI',sans-serif;background:#f4f6f9;margin:0;padding:16px}.container{max-width:1200px;margin:auto;background:white;padding:20px;border-radius:12px}.btn{background:#1e3c72;color:white;padding:8px 16px;text-decoration:none;border-radius:5px;display:inline-block;margin-right:10px}.filters{margin-bottom:20px;display:flex;flex-wrap:wrap;gap:10px;align-items:center}.table-wrapper{overflow-x:auto}table{width:100%;border-collapse:collapse;margin-top:20px}th,td{border:1px solid #ddd;padding:8px;text-align:left}th{background:#1e3c72;color:white}.total-row{font-weight:bold;background:#e9ecef}
    </style>
</head>
<body>
<div class="container">
    <h1>📊 Daily Engineer Hours by Airline</h1>
    <div class="filters">
        <form method="GET" style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
            <label>Month:
                <select name="month">
                    <?php for ($m=1; $m<=12; $m++): ?>
                        <option value="<?php echo $m; ?>" <?php echo $selectedMonth==$m?'selected':''; ?>><?php echo $monthNames[$m]; ?></option>
                    <?php endfor; ?>
                </select>
            </label>
            <label>Year:
                <select name="year">
                    <?php for ($y=date('Y')-2; $y<=date('Y')+2; $y++): ?>
                        <option value="<?php echo $y; ?>" <?php echo $selectedYear==$y?'selected':''; ?>><?php echo $y; ?></option>
                    <?php endfor; ?>
                </select>
            </label>
            <button type="submit" class="btn">Show Report</button>
            <button type="submit" name="export_excel" value="1" class="btn">📎 Export to Excel</button>
            <a href="admin.php" class="btn" style="background:#6c757d;">← Back</a>
        </form>
    </div>
    
    <?php if (empty($dailyHours)): ?>
        <p>No records found for <?php echo $monthNames[$selectedMonth] . ' ' . $selectedYear; ?>.</p>
    <?php else: ?>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>Airline</th>
                        <th>Date</th>
                        <th>Total Engineer Hours</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $grandTotal = 0;
                    foreach ($dailyHours as $airline => $dates):
                        $airlineTotal = 0;
                        foreach ($dates as $date => $hours):
                            $airlineTotal += $hours;
                            $grandTotal += $hours;
                    ?>
                        <tr>
                            <td><?php echo htmlspecialchars($airline); ?></td>
                            <td><?php echo date('M d, Y', strtotime($date)); ?></td>
                            <td><?php echo number_format($hours, 2); ?> hrs</td>
                        </tr>
                    <?php 
                        endforeach;
                    ?>
                        <tr class="total-row">
                            <td colspan="2"><strong><?php echo htmlspecialchars($airline); ?> - Monthly Total</strong></td>
                            <td><strong><?php echo number_format($airlineTotal, 2); ?> hrs</strong></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr class="total-row" style="background:#1e3c72; color:white;">
                        <td colspan="2"><strong>GRAND TOTAL</strong></td>
                        <td><strong><?php echo number_format($grandTotal, 2); ?> hrs</strong></td>
                    </tr>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
</body>
</html>