<?php
require_once 'functions.php';

$airlines = ['CHINA CARGO', 'CHINA S CARGO', 'CHINA E PAX', 'CHINA S PAX', 'BIMAN'];
$errors = [];
$formData = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Combine date and military time into datetime strings
    $arrivalDateTime = !empty($_POST['arrival_date']) && !empty($_POST['arrival_time'])
        ? $_POST['arrival_date'] . ' ' . substr($_POST['arrival_time'], 0, 2) . ':' . substr($_POST['arrival_time'], 2, 2)
        : '';
    $departureDateTime = !empty($_POST['departure_date']) && !empty($_POST['departure_time'])
        ? $_POST['departure_date'] . ' ' . substr($_POST['departure_time'], 0, 2) . ':' . substr($_POST['departure_time'], 2, 2)
        : '';

    $formData = [
        'airline' => $_POST['airline'] ?? '',
        'registration' => $_POST['registration'] ?? '',
        'inbound_flight' => $_POST['inbound_flight'] ?? '',
        'outbound_flight' => $_POST['outbound_flight'] ?? '',
        'arrival_datetime' => $arrivalDateTime,
        'departure_datetime' => $departureDateTime,
        'arrival_gate' => $_POST['arrival_gate'] ?? '',
        'departure_gate' => $_POST['departure_gate'] ?? '',
        'engine_oil1_qty' => $_POST['engine_oil1_qty'] ?? 0,
        'engine_oil2_qty' => $_POST['engine_oil2_qty'] ?? 0,
        'apu_oil_qty' => $_POST['apu_oil_qty'] ?? 0,
        'hydraulic_qty' => $_POST['hydraulic_qty'] ?? 0,
        'tires_serviced' => $_POST['tires_serviced'] ?? 0,
        'engineer1_name' => $_POST['engineer1_name'] ?? '',
        'engineer2_name' => $_POST['engineer2_name'] ?? '',
        'engineer1_stamp' => $_POST['engineer1_stamp'] ?? '',
        'engineer2_stamp' => $_POST['engineer2_stamp'] ?? '',
        'off_schedule' => isset($_POST['off_schedule']) && $_POST['off_schedule'] == 'yes' ? 'yes' : 'no',
        'comments' => $_POST['comments'] ?? ''
    ];
    
    $errors = validateFormData($formData);
    
    if (empty($errors)) {
        $uploadedImages = [];
        if (isset($_FILES['images']) && $_FILES['images']['error'][0] != UPLOAD_ERR_NO_FILE) {
            $uploadedImages = uploadImages($_FILES['images']);
        }
        $employeeHours = calculateEmployeeHours($formData['arrival_datetime'], $formData['departure_datetime']);
        $record = [
            'airline' => $formData['airline'],
            'registration' => $formData['registration'],
            'inbound_flight' => $formData['inbound_flight'],
            'outbound_flight' => $formData['outbound_flight'],
            'arrival_datetime' => $formData['arrival_datetime'],
            'departure_datetime' => $formData['departure_datetime'],
            'arrival_gate' => $formData['arrival_gate'],
            'departure_gate' => $formData['departure_gate'],
            'employee_hours' => $employeeHours,
            'engine_oil1_qty' => (float)$formData['engine_oil1_qty'],
            'engine_oil2_qty' => (float)$formData['engine_oil2_qty'],
            'apu_oil_qty' => (float)$formData['apu_oil_qty'],
            'hydraulic_qty' => (float)$formData['hydraulic_qty'],
            'tires_serviced' => (int)$formData['tires_serviced'],
            'engineer1_name' => $formData['engineer1_name'],
            'engineer2_name' => $formData['engineer2_name'],
            'engineer1_stamp' => $formData['engineer1_stamp'],
            'engineer2_stamp' => $formData['engineer2_stamp'],
            'off_schedule' => $formData['off_schedule'],
            'comments' => $formData['comments'],
            'images' => $uploadedImages
        ];
        if (saveRecord($record)) {
            sendMaintenanceEmail($record, $uploadedImages);
            $success = true;
            $formData = [];
        } else {
            $errors[] = "Failed to save record.";
        }
    }
}

// Helper to split stored datetime into date and time (military)
function splitDateTime($datetime) {
    if (empty($datetime)) return ['date' => '', 'time' => ''];
    $parts = explode(' ', $datetime);
    $date = $parts[0] ?? '';
    $time = isset($parts[1]) ? str_replace(':', '', $parts[1]) : '';
    return ['date' => $date, 'time' => $time];
}
$arrival = splitDateTime($formData['arrival_datetime'] ?? '');
$departure = splitDateTime($formData['departure_datetime'] ?? '');
?>
<!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>Aircraft Maintenance Tracker</title>
    <style>
        *{box-sizing:border-box}body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:#f0f2f5;margin:0;padding:16px}.container{max-width:900px;margin:auto;background:white;padding:20px;border-radius:12px;box-shadow:0 2px 10px rgba(0,0,0,0.1)}h1{text-align:center;color:#1e3c72;margin-bottom:10px;font-size:1.8rem}.subtitle{text-align:center;color:#555;margin-bottom:30px;border-bottom:1px solid #ddd;padding-bottom:15px}.form-group{margin-bottom:20px}label{display:block;font-weight:600;margin-bottom:6px;color:#333}input,select,textarea{width:100%;padding:12px;border:1px solid #ccc;border-radius:6px;font-size:16px}.row{display:flex;gap:16px;flex-wrap:wrap}.col{flex:1;min-width:100%}@media(min-width:640px){.col{min-width:200px}.container{padding:30px}body{padding:20px}}button{background:#1e3c72;color:white;padding:14px 24px;border:none;border-radius:6px;cursor:pointer;font-size:16px;width:100%;font-weight:bold;margin-top:10px}.admin-link{text-align:center;margin-top:20px}.admin-link a{color:#1e3c72;text-decoration:none;display:inline-block;padding:10px}.file-info{font-size:12px;color:#666;margin-top:5px}.success-msg{background:#d4edda;color:#155724;padding:12px;border-radius:6px;margin-bottom:20px}hr{margin:20px 0}.radio-group{display:flex;gap:20px;align-items:center}.radio-group label{font-weight:normal;margin:0}
    </style>
</head>
<body>
<div class="container">
    <h1>✈️ Aircraft Maintenance Activity Log</h1>
    <div class="subtitle">Track Arrivals, Oils, Fluids & Engineers</div>
    <?php if($success): ?>
        <div class="success-msg">✅ Maintenance report submitted successfully! Email sent.</div>
    <?php endif; ?>
    <form action="" method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label>Airline *</label>
            <select name="airline" required>
                <option value="">Select Airline</option>
                <?php foreach($airlines as $airline): ?>
                    <option value="<?php echo htmlspecialchars($airline); ?>" <?php echo (isset($formData['airline']) && $formData['airline']==$airline)?'selected':''; ?>><?php echo htmlspecialchars($airline); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Aircraft Registration Number *</label>
            <input type="text" name="registration" required placeholder="e.g., B-1234, C-FABC" value="<?php echo htmlspecialchars($formData['registration'] ?? ''); ?>">
        </div>
        <div class="row">
            <div class="col"><label>Inbound Flight # *</label><input type="text" name="inbound_flight" required placeholder="e.g., MU207" value="<?php echo htmlspecialchars($formData['inbound_flight'] ?? ''); ?>"></div>
            <div class="col"><label>Outbound Flight # *</label><input type="text" name="outbound_flight" required placeholder="e.g., MU208" value="<?php echo htmlspecialchars($formData['outbound_flight'] ?? ''); ?>"></div>
        </div>
        <div class="row">
            <div class="col">
                <label>Arrival Date *</label>
                <input type="date" name="arrival_date" required value="<?php echo htmlspecialchars($arrival['date']); ?>">
            </div>
            <div class="col">
                <label>Arrival Time (HHMM) *</label>
                <input type="text" name="arrival_time" class="time-input" required placeholder="1430" pattern="[0-2][0-9][0-5][0-9]" maxlength="4" value="<?php echo htmlspecialchars($arrival['time']); ?>">
            </div>
        </div>
        <div class="row">
            <div class="col">
                <label>Arrival Gate</label>
                <input type="text" name="arrival_gate" placeholder="e.g., B12, C45" value="<?php echo htmlspecialchars($formData['arrival_gate'] ?? ''); ?>">
            </div>
            <div class="col">
                <label>Departure Gate</label>
                <input type="text" name="departure_gate" placeholder="e.g., B12, C45" value="<?php echo htmlspecialchars($formData['departure_gate'] ?? ''); ?>">
            </div>
        </div>
        <div class="row">
            <div class="col">
                <label>Departure Date *</label>
                <input type="date" name="departure_date" required value="<?php echo htmlspecialchars($departure['date']); ?>">
            </div>
            <div class="col">
                <label>Departure Time (HHMM) *</label>
                <input type="text" name="departure_time" class="time-input" required placeholder="1730" pattern="[0-2][0-9][0-5][0-9]" maxlength="4" value="<?php echo htmlspecialchars($departure['time']); ?>">
            </div>
        </div>
        <div class="form-group">
            <label>Is this flight off schedule?</label>
            <div class="radio-group">
                <label><input type="radio" name="off_schedule" value="yes" <?php echo (isset($formData['off_schedule']) && $formData['off_schedule']=='yes') ? 'checked' : ''; ?>> Yes</label>
                <label><input type="radio" name="off_schedule" value="no" <?php echo (isset($formData['off_schedule']) && $formData['off_schedule']=='no') ? 'checked' : ''; ?> <?php echo (!isset($formData['off_schedule'])) ? 'checked' : ''; ?>> No</label>
            </div>
        </div>
        <div class="row">
            <div class="col"><label>Engine Oil #1 *</label><input type="number" step="0.1" name="engine_oil1_qty" required value="<?php echo htmlspecialchars($formData['engine_oil1_qty'] ?? 0); ?>"></div>
            <div class="col"><label>Engine Oil #2 *</label><input type="number" step="0.1" name="engine_oil2_qty" required value="<?php echo htmlspecialchars($formData['engine_oil2_qty'] ?? 0); ?>"></div>
            <div class="col"><label>APU Oil *</label><input type="number" step="0.1" name="apu_oil_qty" required value="<?php echo htmlspecialchars($formData['apu_oil_qty'] ?? 0); ?>"></div>
        </div>
        <div class="row">
            <div class="col"><label>Hydraulic Fluid *</label><input type="number" step="0.1" name="hydraulic_qty" required value="<?php echo htmlspecialchars($formData['hydraulic_qty'] ?? 0); ?>"></div>
            <div class="col"><label>Tires Serviced *</label><input type="number" step="1" name="tires_serviced" required value="<?php echo htmlspecialchars($formData['tires_serviced'] ?? 0); ?>"></div>
        </div>
        <div class="row">
            <div class="col">
                <label>Engineer 1 Name *</label>
                <input type="text" name="engineer1_name" id="engineer1_name" list="engineer_list_1" required placeholder="Type or select engineer" value="<?php echo htmlspecialchars($formData['engineer1_name'] ?? ''); ?>">
                <datalist id="engineer_list_1"></datalist>
                <input type="hidden" name="engineer1_stamp" id="engineer1_stamp" value="<?php echo htmlspecialchars($formData['engineer1_stamp'] ?? ''); ?>">
            </div>
            <div class="col">
                <label>Engineer 2 Name</label>
                <input type="text" name="engineer2_name" id="engineer2_name" list="engineer_list_2" placeholder="Type or select engineer" value="<?php echo htmlspecialchars($formData['engineer2_name'] ?? ''); ?>">
                <datalist id="engineer_list_2"></datalist>
                <input type="hidden" name="engineer2_stamp" id="engineer2_stamp" value="<?php echo htmlspecialchars($formData['engineer2_stamp'] ?? ''); ?>">
            </div>
        </div>
        <div class="form-group"><label>Comments</label><textarea name="comments" rows="3"><?php echo htmlspecialchars($formData['comments'] ?? ''); ?></textarea></div>
        <div class="form-group"><label>📸 Upload Pictures</label><input type="file" name="images[]" accept="image/*" multiple><div class="file-info">Max 5MB each</div></div>
        <button type="submit">✅ Submit Maintenance Report</button>
    </form>
    <div class="admin-link"><hr><a href="admin_login.php">🔐 Admin Panel Login</a></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Engineer autocomplete
    const engineer1Input = document.getElementById('engineer1_name');
    const engineer2Input = document.getElementById('engineer2_name');
    const engineer1Stamp = document.getElementById('engineer1_stamp');
    const engineer2Stamp = document.getElementById('engineer2_stamp');
    let engineersList = [];

    fetch('get_engineers.php')
        .then(response => response.json())
        .then(data => {
            if (data.error) return;
            engineersList = data;
            populateDatalist(engineersList);
        })
        .catch(error => console.error(error));

    function populateDatalist(engineers) {
        const datalist1 = document.getElementById('engineer_list_1');
        const datalist2 = document.getElementById('engineer_list_2');
        datalist1.innerHTML = '';
        datalist2.innerHTML = '';
        engineers.forEach(engineer => {
            const displayText = engineer.amo_stamp_number ? `${engineer.full_name} (${engineer.amo_stamp_number})` : engineer.full_name;
            const option1 = document.createElement('option');
            option1.value = displayText;
            datalist1.appendChild(option1);
            const option2 = option1.cloneNode(true);
            datalist2.appendChild(option2);
        });
    }

    function updateStampField(inputEl, stampField) {
        const selectedValue = inputEl.value;
        const matching = engineersList.find(eng => {
            const display = eng.amo_stamp_number ? `${eng.full_name} (${eng.amo_stamp_number})` : eng.full_name;
            return display === selectedValue;
        });
        stampField.value = matching ? matching.amo_stamp_number : '';
    }

    engineer1Input.addEventListener('change', () => updateStampField(engineer1Input, engineer1Stamp));
    engineer2Input.addEventListener('change', () => updateStampField(engineer2Input, engineer2Stamp));

    // Military time input: auto-format and restrict to 4 digits
    const timeInputs = document.querySelectorAll('.time-input');
    timeInputs.forEach(input => {
        input.addEventListener('input', function(e) {
            let val = this.value.replace(/\D/g, '').slice(0,4);
            if (val.length === 4) {
                let hours = parseInt(val.substring(0,2));
                let mins = parseInt(val.substring(2,4));
                if (hours >= 0 && hours <= 23 && mins >= 0 && mins <= 59) {
                    this.value = val;
                } else {
                    this.value = val.substring(0,2);
                }
            } else {
                this.value = val;
            }
        });
    });
});
</script>
<?php if(!empty($errors)): ?>
<script>alert("Please fix:\n- <?php echo implode("\\n- ", array_map('htmlspecialchars', $errors)); ?>");</script>
<?php endif; ?>
</body>
</html>