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

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

// Handle deletion
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    deleteRecord($_GET['delete']);
    header('Location: admin.php?deleted=1');
    exit;
}

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

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

usort($records, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

$successMsg = '';
if (isset($_GET['deleted'])) {
    $successMsg = 'Record deleted successfully.';
}
if (isset($_GET['updated'])) {
    $successMsg = 'Record updated successfully.';
}

$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, maximum-scale=1.0, user-scalable=yes">
    <title>Admin Dashboard - Maintenance History</title>
    <style>
        * { box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', sans-serif;
            background: #f4f6f9;
            margin: 0;
            padding: 12px;
        }
        .container {
            max-width: 1400px;
            margin: auto;
            background: white;
            padding: 16px;
            border-radius: 12px;
        }
        h1 { margin-top: 0; font-size: 1.6rem; }
        .top-bar {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-bottom: 20px;
        }
        .top-bar-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        .filters {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
            margin-bottom: 20px;
            background: #f8f9fa;
            padding: 12px;
            border-radius: 8px;
        }
        .btn {
            background: #1e3c72;
            color: white;
            padding: 8px 14px;
            text-decoration: none;
            border-radius: 5px;
            display: inline-block;
            font-size: 0.9rem;
            text-align: center;
        }
        .btn-edit { background: #ffc107; color: #333; }
        .btn-danger { background: #dc3545; }
        .btn-secondary { background: #6c757d; }
        .success-banner {
            background: #d4edda;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .table-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            margin-top: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1100px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
            vertical-align: top;
        }
        th { background: #1e3c72; color: white; }
        tr:nth-child(even) { background: #f9f9f9; }
        .image-thumb {
            max-width: 50px;
            max-height: 50px;
            margin: 2px;
        }
        .action-links a {
            margin-right: 8px;
            text-decoration: none;
            display: inline-block;
            margin-bottom: 5px;
        }

        @media (max-width: 640px) {
            .table-wrapper {
                overflow-x: visible;
            }
            table, thead, tbody, th, td, tr {
                display: block;
            }
            thead {
                display: none;
            }
            tr {
                border: 1px solid #ddd;
                border-radius: 8px;
                margin-bottom: 16px;
                padding: 12px;
                background: white;
            }
            td {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                border: none;
                padding: 8px 0;
                border-bottom: 1px solid #eee;
            }
            td:last-child {
                border-bottom: none;
            }
            td:before {
                content: attr(data-label);
                font-weight: bold;
                width: 40%;
                min-width: 120px;
                color: #1e3c72;
            }
            .action-links {
                justify-content: flex-start;
                gap: 12px;
            }
            .action-links a {
                margin-right: 12px;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: 12px;
            }
            .btn {
                padding: 8px 12px;
                font-size: 0.8rem;
            }
            td:before {
                width: 35%;
                min-width: 100px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="top-bar">
        <h1>📋 Maintenance History</h1>
        <div class="top-bar-buttons">
            <a href="daily_hours_report.php" class="btn">📊 Daily Hours Report</a>
            <a href="airline_report.php" class="btn">📊 Airline Hours</a>
            <a href="engineer_hours.php" class="btn">👨‍🔧 Engineer Hours</a>
            <a href="invoice.php" class="btn">📄 Monthly Invoice</a>
            <a href="logout.php" class="btn btn-secondary">🚪 Logout</a>
        </div>
    </div>
    
    <div class="filters">
        <form method="GET" style="display: flex; gap: 8px; 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">Filter</button>
            <a href="admin.php" class="btn btn-secondary">Reset</a>
        </form>
    </div>
    
    <?php if ($successMsg): ?>
        <div class="success-banner"><?php echo $successMsg; ?></div>
    <?php endif; ?>
    
    <?php if (empty($records)): ?>
        <p>No maintenance records found for <?php echo $monthNames[$selectedMonth] . ' ' . $selectedYear; ?>.</p>
    <?php else: ?>
        <p><strong>Showing <?php echo count($records); ?> record(s)</strong> for <?php echo $monthNames[$selectedMonth] . ' ' . $selectedYear; ?></p>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>ID/Date</th>
                        <th>Airline/Reg</th>
                        <th>Flight (In/Out)</th>
                        <th>Arrival Gate</th>
                        <th>Departure Gate</th>
                        <th>Times (Arr/Dep)</th>
                        <th>Off Schedule</th>
                        <th>Hours (per eng)</th>
                        <th>Total Labor Hrs</th>
                        <th>Oils (E1/E2/APU)</th>
                        <th>Hyd/Tires</th>
                        <th>Engineers</th>
                        <th>Images</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($records as $record): ?>
                    <?php 
                        $totalLabor = getTotalEngineerHoursForRecord($record);
                        $oilSummary = "#1: {$record['engine_oil1_qty']} / #2: {$record['engine_oil2_qty']} / APU: {$record['apu_oil_qty']}";
                        $hydTires = "Hyd: {$record['hydraulic_qty']} / Tires: {$record['tires_serviced']}";
                        $offSchedule = (isset($record['off_schedule']) && $record['off_schedule'] == 'yes') ? 'Yes' : 'No';
                    ?>
                    <tr>
                        <td data-label="ID/Date"><?php echo htmlspecialchars(substr($record['id'], -6)); ?><br><small><?php echo htmlspecialchars($record['created_at']); ?></small></td>
                        <td data-label="Airline/Reg"><?php echo htmlspecialchars($record['airline']); ?><br><?php echo htmlspecialchars($record['registration']); ?></td>
                        <td data-label="Flight (In/Out)"><?php echo htmlspecialchars($record['inbound_flight']); ?> → <?php echo htmlspecialchars($record['outbound_flight']); ?></td>
                        <td data-label="Arrival Gate"><?php echo htmlspecialchars($record['arrival_gate'] ?? ''); ?></td>
                        <td data-label="Departure Gate"><?php echo htmlspecialchars($record['departure_gate'] ?? ''); ?></td>
                        <td data-label="Times (Arr/Dep)">Arr: <?php echo htmlspecialchars($record['arrival_datetime']); ?><br>Dep: <?php echo htmlspecialchars($record['departure_datetime']); ?></td>
                        <td data-label="Off Schedule"><?php echo $offSchedule; ?></td>
                        <td data-label="Hours (per eng)"><?php echo $record['employee_hours']; ?> hrs</span></td>
                        <td data-label="Total Labor Hrs"><?php echo $totalLabor; ?> hrs</span></td>
                        <td data-label="Oils"><?php echo $oilSummary; ?></td>
                        <td data-label="Hyd/Tires"><?php echo $hydTires; ?></td>
                        <td data-label="Engineers"><?php echo htmlspecialchars($record['engineer1_name']); ?><br><?php echo htmlspecialchars($record['engineer2_name']); ?></td>
                        <td data-label="Images">
                            <?php if (!empty($record['images'])): ?>
                                <?php foreach ($record['images'] as $img): ?>
                                    <a href="<?php echo $img; ?>" target="_blank"><img src="<?php echo $img; ?>" class="image-thumb" alt="thumb"></a>
                                <?php endforeach; ?>
                            <?php else: ?>—<?php endif; ?>
                        </span></td>
                        <td data-label="Actions" class="action-links">
                            <a href="edit.php?id=<?php echo $record['id']; ?>" class="btn-edit" style="background:#ffc107; color:#333; padding:4px 8px; display:inline-block;">✏️ Edit</a>
                            <a href="admin.php?delete=<?php echo $record['id']; ?>" onclick="return confirm('Delete this record permanently?')" style="color:red; display:inline-block;">🗑️ Delete</a>
                        </span></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
</body>
</html>