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

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

$id = $_GET['id'] ?? '';
if (empty($id)) {
    header('Location: admin.php');
    exit;
}

$records = getRecords();
$record = null;
foreach ($records as $r) {
    if ($r['id'] == $id) {
        $record = $r;
        break;
    }
}
if (!$record) {
    header('Location: admin.php');
    exit;
}

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

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($record['arrival_datetime'] ?? '');
$departure = splitDateTime($record['departure_datetime'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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)
        : '';

    $updatedData = [
        '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' => floatval($_POST['engine_oil1_qty'] ?? 0),
        'engine_oil2_qty' => floatval($_POST['engine_oil2_qty'] ?? 0),
        'apu_oil_qty' => floatval($_POST['apu_oil_qty'] ?? 0),
        'hydraulic_qty' => floatval($_POST['hydraulic_qty'] ?? 0),
        'tires_serviced' => intval($_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($updatedData);
    
    if (empty($errors)) {
        $updatedData['employee_hours'] = calculateEmployeeHours($updatedData['arrival_datetime'], $updatedData['departure_datetime']);
        
        if (isset($_FILES['images']) && $_FILES['images']['error'][0] != UPLOAD_ERR_NO_FILE) {
            $newImages = uploadImages($_FILES['images']);
            $updatedData['images'] = array_merge($record['images'] ?? [], $newImages);
        } else {
            $updatedData['images'] = $record['images'] ?? [];
        }
        
        if (isset($_POST['delete_images']) && is_array($_POST['delete_images'])) {
            foreach ($_POST['delete_images'] as $imgToDelete) {
                $fullPath = __DIR__ . '/' . $imgToDelete;
                if (file_exists($fullPath)) unlink($fullPath);
                $key = array_search($imgToDelete, $updatedData['images']);
                if ($key !== false) unset($updatedData['images'][$key]);
            }
            $updatedData['images'] = array_values($updatedData['images']);
        }
        
        if (updateRecord($id, $updatedData)) {
            $success = true;
            $records = getRecords();
            foreach ($records as $r) {
                if ($r['id'] == $id) {
                    $record = $r;
                    break;
                }
            }
            $arrival = splitDateTime($record['arrival_datetime']);
            $departure = splitDateTime($record['departure_datetime']);
        } else {
            $errors[] = "Failed to update record.";
        }
    } else {
        $arrival = ['date' => $_POST['arrival_date'] ?? '', 'time' => $_POST['arrival_time'] ?? ''];
        $departure = ['date' => $_POST['departure_date'] ?? '', 'time' => $_POST['departure_time'] ?? ''];
    }
}
?>
<!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>Edit Maintenance Record</title>
    <style>
        *{box-sizing:border-box}body{font-family:'Segoe UI',sans-serif;background:#f0f2f5;margin:0;padding:16px}.container{max-width:900px;margin:auto;background:white;padding:20px;border-radius:12px}.form-group{margin-bottom:20px}label{font-weight:600;display:block;margin-bottom:6px}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%;margin-top:10px}.btn-secondary{background:#6c757d;text-decoration:none;display:inline-block;text-align:center;padding:12px 20px;border-radius:6px;color:white}.image-list{display:flex;flex-wrap:wrap;gap:15px;margin-top:10px}.image-item{border:1px solid #ddd;padding:8px;border-radius:6px;text-align:center}.image-item img{max-width:100px;max-height:100px}.error-msg,.success-msg{padding:10px;border-radius:6px;margin-bottom:20px}.error-msg{background:#f8d7da;color:#721c24}.success-msg{background:#d4edda;color:#155724}.radio-group{display:flex;gap:20px;align-items:center}.radio-group label{font-weight:normal;margin:0}
    </style>
</head>
<body>
<div class="container">
    <h1>✏️ Edit Maintenance Record</h1>
    <p><a href="admin.php" class="btn-secondary" style="display:inline-block; text-decoration:none;">← Back to Dashboard</a></p>
    <?php if ($success): ?><div class="success-msg">✅ Record updated successfully!</div><?php endif; ?>
    <?php if (!empty($errors)): ?><div class="error-msg"><strong>Errors:</strong><br><?php echo implode('<br>', array_map('htmlspecialchars', $errors)); ?></div><?php endif; ?>
    <form action="" method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label>Airline *</label>
            <select name="airline" required>
                <?php foreach($airlines as $airline): ?>
                    <option value="<?php echo htmlspecialchars($airline); ?>" <?php echo ($record['airline']==$airline)?'selected':''; ?>><?php echo htmlspecialchars($airline); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Aircraft Registration *</label>
            <input type="text" name="registration" required value="<?php echo htmlspecialchars($record['registration']); ?>">
        </div>
        <div class="row">
            <div class="col"><label>Inbound Flight *</label><input type="text" name="inbound_flight" required value="<?php echo htmlspecialchars($record['inbound_flight']); ?>"></div>
            <div class="col"><label>Outbound Flight *</label><input type="text" name="outbound_flight" required value="<?php echo htmlspecialchars($record['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($record['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($record['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($record['off_schedule']) && $record['off_schedule']=='yes') ? 'checked' : ''; ?>> Yes</label>
                <label><input type="radio" name="off_schedule" value="no" <?php echo (isset($record['off_schedule']) && $record['off_schedule']=='no') ? 'checked' : ''; ?> <?php echo (!isset($record['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 $record['engine_oil1_qty']; ?>"></div>
            <div class="col"><label>Engine Oil #2</label><input type="number" step="0.1" name="engine_oil2_qty" required value="<?php echo $record['engine_oil2_qty']; ?>"></div>
            <div class="col"><label>APU Oil</label><input type="number" step="0.1" name="apu_oil_qty" required value="<?php echo $record['apu_oil_qty']; ?>"></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 $record['hydraulic_qty']; ?>"></div>
            <div class="col"><label>Tires Serviced</label><input type="number" step="1" name="tires_serviced" required value="<?php echo $record['tires_serviced']; ?>"></div>
        </div>
        <div class="row">
            <div class="col">
                <label>Engineer 1 *</label>
                <input type="text" name="engineer1_name" id="engineer1_name" list="engineer_list_1" required value="<?php echo htmlspecialchars($record['engineer1_name']); ?>">
                <datalist id="engineer_list_1"></datalist>
                <input type="hidden" name="engineer1_stamp" id="engineer1_stamp" value="<?php echo htmlspecialchars($record['engineer1_stamp'] ?? ''); ?>">
            </div>
            <div class="col">
                <label>Engineer 2</label>
                <input type="text" name="engineer2_name" id="engineer2_name" list="engineer_list_2" value="<?php echo htmlspecialchars($record['engineer2_name']); ?>">
                <datalist id="engineer_list_2"></datalist>
                <input type="hidden" name="engineer2_stamp" id="engineer2_stamp" value="<?php echo htmlspecialchars($record['engineer2_stamp'] ?? ''); ?>">
            </div>
        </div>
        <div class="form-group"><label>Comments</label><textarea name="comments" rows="3"><?php echo htmlspecialchars($record['comments']); ?></textarea></div>
        <div class="form-group">
            <label>Current Images</label>
            <div class="image-list">
                <?php if (!empty($record['images'])): ?>
                    <?php foreach ($record['images'] as $img): ?>
                        <div class="image-item"><img src="<?php echo $img; ?>"><label><input type="checkbox" name="delete_images[]" value="<?php echo htmlspecialchars($img); ?>"> Delete</label></div>
                    <?php endforeach; ?>
                <?php else: ?><p>No images attached.</p><?php endif; ?>
            </div>
        </div>
        <div class="form-group"><label>Add New Images</label><input type="file" name="images[]" accept="image/*" multiple><small>Select one or more</small></div>
        <button type="submit">💾 Save Changes</button>
        <a href="admin.php" class="btn-secondary" style="display:inline-block; margin-top:10px; text-align:center;">Cancel</a>
    </form>
</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 formatting
    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>
</body>
</html>