<?php
// ==========================================
// submit.php - Handle form submission, uploads, email, storage
// ==========================================
require_once 'functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

// Validate form data
$errors = validateFormData($_POST);
if (!empty($errors)) {
    // Display errors and exit (simplified)
    echo "<h2>Validation Errors</h2><ul>";
    foreach ($errors as $err) {
        echo "<li>" . htmlspecialchars($err) . "</li>";
    }
    echo "</ul><a href='index.php'>Go Back</a>";
    exit;
}

// Handle file uploads
$uploadedImages = [];
if (isset($_FILES['images']) && $_FILES['images']['error'][0] != UPLOAD_ERR_NO_FILE) {
    $uploadedImages = uploadImages($_FILES['images']);
}

// Calculate employee hours from arrival/departure
$employeeHours = calculateEmployeeHours($_POST['arrival_datetime'], $_POST['departure_datetime']);

// Build record array
$record = [
    'airline' => $_POST['airline'],
    'inbound_flight' => $_POST['inbound_flight'],
    'outbound_flight' => $_POST['outbound_flight'],
    'arrival_datetime' => $_POST['arrival_datetime'],
    'departure_datetime' => $_POST['departure_datetime'],
    'employee_hours' => $employeeHours,
    'engine_oil1_qty' => floatval($_POST['engine_oil1_qty']),
    'engine_oil2_qty' => floatval($_POST['engine_oil2_qty']),
    'apu_oil_qty' => floatval($_POST['apu_oil_qty']),
    'hydraulic_qty' => floatval($_POST['hydraulic_qty']),
    'tires_serviced' => intval($_POST['tires_serviced']),
    'engineer1_name' => $_POST['engineer1_name'],
    'engineer2_name' => $_POST['engineer2_name'] ?? '',
    'comments' => $_POST['comments'] ?? '',
    'images' => $uploadedImages
];

// Save record to JSON file
if (saveRecord($record)) {
    // Send email notification
    sendMaintenanceEmail($record, $uploadedImages);
    header('Location: index.php?success=1');
    exit;
} else {
    echo "Error saving record. Please contact administrator.";
    exit;
}
?>