<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('memory_limit', '512M');

session_start();
require_once 'functions.php';

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

$airlines = ['CHINA CARGO', 'CHINA S CARGO', 'CHINA E PAX', 'CHINA S PAX', 'BIMAN', 'ALL'];
$selectedAirline = isset($_GET['airline']) ? $_GET['airline'] : 'ALL';
$selectedMonth = isset($_GET['month']) ? intval($_GET['month']) : date('m');
$selectedYear = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

$allRecords = getRecords();
$filteredRecords = [];

foreach ($allRecords as $record) {
    $arrivalDate = new DateTime($record['arrival_datetime']);
    if ($arrivalDate->format('m') == $selectedMonth && $arrivalDate->format('Y') == $selectedYear) {
        if ($selectedAirline == 'ALL' || $record['airline'] == $selectedAirline) {
            $filteredRecords[] = $record;
        }
    }
}

// Handle export
if (isset($_GET['export_excel']) && $_GET['export_excel'] == '1') {
    while (ob_get_level()) ob_end_clean();
    exportToExcel($filteredRecords, $selectedMonth, $selectedYear, $selectedAirline);
    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>Invoice - Techni-Air MRO</title>
    <style>
        body{font-family:'Segoe UI',sans-serif;background:#e9ecef;margin:0;padding:16px}
        .invoice{max-width:1200px;margin:auto;background:white;padding:20px;border-radius:12px}
        .header{text-align:center;border-bottom:2px solid #1e3c72;padding-bottom:15px;margin-bottom:25px}
        .btn-print{background:#1e3c72;color:white;padding:8px 16px;border:none;border-radius:5px;cursor:pointer;margin-right:10px}
        .filters{margin-bottom:20px;display:flex;flex-wrap:wrap;gap:10px;align-items:center}
        a{text-decoration:none;color:white;background:#6c757d;padding:8px 15px;border-radius:5px}
        table{width:100%;border-collapse:collapse}
        th,td{border:1px solid #ccc;padding:8px;text-align:left}
        th{background:#1e3c72;color:white}
    </style>
</head>
<body>
<div class="invoice">
    <div class="header"><h1>Techni-Air MRO</h1><h2>Monthly Maintenance Invoice</h2></div>
    <div class="filters">
        <form method="GET" style="display:flex; flex-wrap:wrap; gap:10px; align-items:center;">
            <label>Airline:
                <select name="airline">
                    <?php foreach($airlines as $a): ?>
                        <option value="<?php echo $a; ?>" <?php echo $selectedAirline==$a?'selected':''; ?>><?php echo $a; ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <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')+1;$y++): ?>
                        <option value="<?php echo $y; ?>" <?php echo $selectedYear==$y?'selected':''; ?>><?php echo $y; ?></option>
                    <?php endfor; ?>
                </select>
            </label>
            <button type="submit" class="btn-print">Refresh</button>
            <button type="submit" name="export_excel" value="1" class="btn-print">Export to CSV</button>
            <a href="admin.php">← Back</a>
        </form>
    </div>
    <?php if(empty($filteredRecords)): ?>
        <p>No records found for selected airline and period.</p>
    <?php else: ?>
        <p><strong><?php echo $selectedAirline; ?></strong> – <?php echo $monthNames[$selectedMonth] . ' ' . $selectedYear; ?> (<?php echo count($filteredRecords); ?> records)</p>
        <table>
            <thead><tr><th>Date</th><th>Registration</th><th>Flight</th><th>Engine Oils</th><th>Hydraulic</th><th>Tires</th><th>Labor Hours</th></tr></thead>
            <tbody>
                <?php foreach($filteredRecords as $rec): 
                    $totalLabor = getTotalEngineerHoursForRecord($rec);
                ?>
                <tr>
                    <td><?php echo date('Y-m-d', strtotime($rec['arrival_datetime'])); ?></td>
                    <td><?php echo htmlspecialchars($rec['registration']); ?></td>
                    <td><?php echo htmlspecialchars($rec['inbound_flight']); ?>/<?php echo htmlspecialchars($rec['outbound_flight']); ?></td>
                    <td><?php echo $rec['engine_oil1_qty']+$rec['engine_oil2_qty']+$rec['apu_oil_qty']; ?></td>
                    <td><?php echo $rec['hydraulic_qty']; ?></td>
                    <td><?php echo $rec['tires_serviced']; ?></td>
                    <td><?php echo $totalLabor; ?> hrs</td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
</body>
</html>