<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt');

// Load PHPMailer if available
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
} else {
    if (file_exists(__DIR__ . '/phpmailer/Exception.php')) {
        require_once __DIR__ . '/phpmailer/Exception.php';
        require_once __DIR__ . '/phpmailer/PHPMailer.php';
        require_once __DIR__ . '/phpmailer/SMTP.php';
    }
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

define('DATA_DIR', __DIR__ . '/data');
define('UPLOADS_DIR', __DIR__ . '/uploads');
define('RECORDS_FILE', DATA_DIR . '/records.json');

if (!file_exists(DATA_DIR)) mkdir(DATA_DIR, 0755, true);
if (!file_exists(UPLOADS_DIR)) mkdir(UPLOADS_DIR, 0755, true);

// -------------------------------
// Core functions
// -------------------------------
function getRecords() {
    if (!file_exists(RECORDS_FILE)) return [];
    $content = file_get_contents(RECORDS_FILE);
    return $content ? json_decode($content, true) : [];
}

function saveRecord($record) {
    $records = getRecords();
    $record['id'] = uniqid();
    $record['created_at'] = date('Y-m-d H:i:s');
    $records[] = $record;
    $fp = fopen(RECORDS_FILE, 'w');
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, json_encode($records, JSON_PRETTY_PRINT));
        flock($fp, LOCK_UN);
        fclose($fp);
        return true;
    }
    fclose($fp);
    return false;
}

function updateRecords($records) {
    $fp = fopen(RECORDS_FILE, 'w');
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, json_encode($records, JSON_PRETTY_PRINT));
        flock($fp, LOCK_UN);
        fclose($fp);
        return true;
    }
    fclose($fp);
    return false;
}

function deleteRecord($id) {
    $records = getRecords();
    foreach ($records as $key => $record) {
        if ($record['id'] == $id) {
            if (!empty($record['images'])) {
                foreach ($record['images'] as $img) {
                    $path = __DIR__ . '/' . $img;
                    if (file_exists($path)) unlink($path);
                }
            }
            unset($records[$key]);
            return updateRecords(array_values($records));
        }
    }
    return false;
}

function updateRecord($id, $newData) {
    $records = getRecords();
    foreach ($records as $key => $record) {
        if ($record['id'] == $id) {
            $newData['id'] = $record['id'];
            $newData['created_at'] = $record['created_at'];
            if (!isset($newData['images'])) $newData['images'] = $record['images'] ?? [];
            $records[$key] = $newData;
            return updateRecords($records);
        }
    }
    return false;
}

function filterRecordsByMonthYear($records, $month, $year) {
    return array_filter($records, function($r) use ($month, $year) {
        $d = new DateTime($r['arrival_datetime']);
        return $d->format('m') == $month && $d->format('Y') == $year;
    });
}

function calculateEmployeeHours($arrival, $departure) {
    $a = new DateTime($arrival);
    $d = new DateTime($departure);
    if ($d <= $a) return 0;
    $diff = $d->diff($a);
    $hours = $diff->h + ($diff->i/60) + ($diff->days*24);
    if ($hours < 4) return 4.0;
    return ceil($hours * 2) / 2;
}

function getTotalEngineerHoursForRecord($record) {
    $base = $record['employee_hours'];
    return (!empty($record['engineer2_name']) && trim($record['engineer2_name']) != '') ? $base * 2 : $base;
}

function getEngineerHoursByMonthYear($month, $year) {
    $all = getRecords();
    $filtered = filterRecordsByMonthYear($all, $month, $year);
    $hours = [];
    foreach ($filtered as $r) {
        $h = $r['employee_hours'];
        $e1 = trim($r['engineer1_name']);
        if ($e1) $hours[$e1] = ($hours[$e1] ?? 0) + $h;
        $e2 = trim($r['engineer2_name']);
        if ($e2) $hours[$e2] = ($hours[$e2] ?? 0) + $h;
    }
    arsort($hours);
    return $hours;
}

function sendMaintenanceEmail($record, $uploadedFiles) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp-relay.brevo.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'YOUR_BREVO_LOGIN_EMAIL@example.com';
        $mail->Password   = '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';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        $mail->setFrom('noreply@rxaero.com', 'Techni-Air MRO');
        $mail->addAddress('yyzops@rxaero.com');
        $mail->addCC('rxaero.mro@gmail.com');
        $mail->isHTML(true);
        $mail->Subject = 'Maintenance Report - ' . $record['airline'] . ' ' . $record['registration'];
        $body = "<html><body><h2>Aircraft Maintenance Activity Report</h2><table border='1'>";
        $body .= "<tr><th>Airline</th>工作领导小组{$record['airline']} </span></td></span>";
        $body .= "<tr><th>Registration</th>工作领导小组{$record['registration']} </span></td></span>";
        $body .= "<tr><th>Inbound</th>工作领导小组{$record['inbound_flight']} </span></td></span>";
        $body .= "<tr><th>Outbound</th>工作领导小组{$record['outbound_flight']} </span></td></span>";
        $body .= "<tr><th>Arrival</th>工作领导小组{$record['arrival_datetime']} </span></td></span>";
        $body .= "<tr><th>Departure</th>工作领导小组{$record['departure_datetime']} </span></td></span>";
        $body .= "<tr><th>Arrival Gate</th>工作领导小组" . ($record['arrival_gate'] ?? '') . " </span></td></span>";
        $body .= "<tr><th>Departure Gate</th>工作领导小组" . ($record['departure_gate'] ?? '') . " </span></td></span>";
        $body .= "<tr><th>Off Schedule</th>工作领导小组" . ($record['off_schedule'] ?? 'no') . " </span></td></span>";
        $body .= "<tr><th>Hours/Eng</th>工作领导小组{$record['employee_hours']} hrs</span></td></span>";
        $body .= "<tr><th>Total Labor</th>工作领导小组" . getTotalEngineerHoursForRecord($record) . " hrs</span></td></span>";
        $body .= "</table></body></html>";
        $mail->Body = $body;
        $mail->AltBody = strip_tags($body);
        foreach ($uploadedFiles as $file) {
            $path = __DIR__ . '/' . $file;
            if (file_exists($path)) $mail->addAttachment($path);
        }
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email failed: " . $mail->ErrorInfo);
        return false;
    }
}

function uploadImages($files) {
    $paths = [];
    $allowed = ['image/jpeg','image/png','image/gif','image/jpg'];
    if (empty($files['name'][0])) return $paths;
    for ($i=0; $i<count($files['name']); $i++) {
        if ($files['error'][$i] != UPLOAD_ERR_OK) continue;
        $type = mime_content_type($files['tmp_name'][$i]);
        if (!in_array($type, $allowed)) continue;
        if ($files['size'][$i] > 5*1024*1024) continue;
        $ext = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
        $name = uniqid() . '_' . time() . '.' . $ext;
        $dest = UPLOADS_DIR . '/' . $name;
        if (move_uploaded_file($files['tmp_name'][$i], $dest)) {
            $paths[] = 'uploads/' . $name;
        }
    }
    return $paths;
}

function validateFormData($data) {
    $errors = [];
    $required = ['airline','registration','inbound_flight','outbound_flight','arrival_datetime','departure_datetime'];
    foreach ($required as $f) {
        if (empty($data[$f])) $errors[] = ucfirst(str_replace('_',' ',$f)) . " required.";
    }
    if (!empty($data['arrival_datetime']) && !empty($data['departure_datetime'])) {
        $a = new DateTime($data['arrival_datetime']);
        $d = new DateTime($data['departure_datetime']);
        if ($d <= $a) $errors[] = "Departure must be after arrival.";
    }
    $nums = ['engine_oil1_qty','engine_oil2_qty','apu_oil_qty','hydraulic_qty','tires_serviced'];
    foreach ($nums as $n) {
        if (!isset($data[$n]) || !is_numeric($data[$n]) || $data[$n] < 0) {
            $errors[] = ucfirst(str_replace('_',' ',$n)) . " must be >=0.";
        }
    }
    return $errors;
}

// -------------------------------
// CSV Export for Monthly Invoice (with gates and off-schedule)
// -------------------------------
function exportToExcel($records, $month, $year, $airline = 'ALL') {
    $filename = 'TechniAir_Invoice_' . $airline . '_' . $year . '_' . str_pad($month, 2, '0', STR_PAD_LEFT) . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    $output = fopen('php://output', 'w');

    // Calculations
    $numRecords = count($records);
    $totalEligibleLaborHours = 0;
    $totalEngineOilQty = 0;
    $totalHydraulicQty = 0;
    $totalTiresServiced = 0;
    $hasDefrost = false;
    $offScheduleCount = 0;

    foreach ($records as $rec) {
        $arr = new DateTime($rec['arrival_datetime']);
        $dep = new DateTime($rec['departure_datetime']);
        $diffHours = ($dep->getTimestamp() - $arr->getTimestamp()) / 3600;
        if ($diffHours > 4) {
            $totalEligibleLaborHours += getTotalEngineerHoursForRecord($rec);
        }
        if (isset($rec['off_schedule']) && $rec['off_schedule'] == 'yes') {
            $offScheduleCount++;
        }
        $totalEngineOilQty += $rec['engine_oil1_qty'] + $rec['engine_oil2_qty'] + $rec['apu_oil_qty'];
        $totalHydraulicQty += $rec['hydraulic_qty'];
        $totalTiresServiced += $rec['tires_serviced'];
        if (stripos($rec['comments'], 'defrost') !== false) $hasDefrost = true;
    }

    $offScheduleHours = $offScheduleCount * 4;

    $lineItems = [];
    if ($totalEligibleLaborHours > 0) $lineItems[] = ['desc'=>'Technical Handling','qty'=>$totalEligibleLaborHours,'uom'=>'HR','rate'=>130.00];
    if ($numRecords > 0) $lineItems[] = ['desc'=>'Transit Check','qty'=>$numRecords,'uom'=>'EA','rate'=>650.00];
    if ($totalEngineOilQty > 0) $lineItems[] = ['desc'=>'Engine Oil','qty'=>$totalEngineOilQty,'uom'=>'EA','rate'=>27.50];
    if ($totalHydraulicQty > 0) $lineItems[] = ['desc'=>'Hydraulic Servicing','qty'=>$totalHydraulicQty,'uom'=>'CAN','rate'=>57.54];
    if ($totalTiresServiced > 0) {
        $lineItems[] = ['desc'=>'Wheel Change','qty'=>$totalTiresServiced,'uom'=>'EA','rate'=>950.00];
        $lineItems[] = ['desc'=>'Shipping and Handling*','qty'=>$totalTiresServiced,'uom'=>'EA','rate'=>130.00];
    }
    if ($totalHydraulicQty > 0) $lineItems[] = ['desc'=>'IDG Servicing','qty'=>$totalHydraulicQty,'uom'=>'EA','rate'=>150.00];
    if ($numRecords > 0) $lineItems[] = ['desc'=>'Equipment (high lift)','qty'=>$numRecords,'uom'=>'HR','rate'=>250.00];
    if ($hasDefrost) $lineItems[] = ['desc'=>'Waste Line Defrost','qty'=>1,'uom'=>'EA','rate'=>400.00];
    if ($offScheduleHours > 0) {
        $lineItems[] = ['desc'=>'Off Schedule Technical Handling','qty'=>$offScheduleHours,'uom'=>'HR','rate'=>130.00];
    }

    $displayAirline = ($airline == 'ALL' ? 'ALL AIRLINES' : $airline);
    $invoiceMonth = date('M-y', mktime(0,0,0,$month,1,$year));
    fputcsv($output, ['TECHNI-AIR 2000']);
    fputcsv($output, ['AIRCRAFT MAINTENANCE SERVICES']);
    fputcsv($output, ['INVOICE FOR: ' . $displayAirline]);
    fputcsv($output, []);
    fputcsv($output, ['Billed Entity Name', $displayAirline]);
    fputcsv($output, ['420-121 Bloor Street East, Toronto, Ontario M4W-3M5, Canada']);
    fputcsv($output, []);
    fputcsv($output, ['Invoice Number', rand(3000,9999)]);
    fputcsv($output, ['Month/Year', $invoiceMonth]);
    fputcsv($output, ['Currency', 'CAD']);
    fputcsv($output, []);
    fputcsv($output, ['For Billing details, please refer to attached supporting']);
    fputcsv($output, []);

    fputcsv($output, ['Line #','Date of Service','Description','Quantity','UOM','Unit Price','Base Amount','HST (13%)','Line Amount']);
    $line = 1;
    $subtotal = 0;
    foreach ($lineItems as $item) {
        $base = $item['qty'] * $item['rate'];
        $hst = round($base * 0.13, 2);
        $lineTotal = $base + $hst;
        $subtotal += $base;
        fputcsv($output, [
            $line, $invoiceMonth, $item['desc'], $item['qty'], $item['uom'],
            number_format($item['rate'],2), number_format($base,2), number_format($hst,2), number_format($lineTotal,2)
        ]);
        $line++;
    }

    $gtaa = round($subtotal * 0.05, 2);
    $hstTotal = round($subtotal * 0.13, 2);
    $grandTotal = $subtotal + $gtaa + $hstTotal;
    fputcsv($output, []);
    fputcsv($output, ['', '', '', '', '', '', 'SUB TOTAL', '', number_format($subtotal,2)]);
    fputcsv($output, ['', '', '', '', '', '', 'GTAA 5%', '', number_format($gtaa,2)]);
    fputcsv($output, ['', '', '', '', '', '', 'HST 13%', '', number_format($hstTotal,2)]);
    fputcsv($output, ['', '', '', '', '', '', 'GRAND TOTAL CAD', '', number_format($grandTotal,2)]);
    fputcsv($output, []);
    fputcsv($output, ['*NEW NOSE WHEEL/MAIN WHEEL HANDLED BY SCC']);

    fputcsv($output, []);
    fputcsv($output, ['Payment Method : Bank Transfer']);
    fputcsv($output, ['Company Name: Techni-Air 2000']);
    fputcsv($output, ['Bank Name : National Bank of Canada']);
    fputcsv($output, ['Bank Address : 1265 CHEMIN DU TREMBLAY, LONGUEUIL QC J4N 0G3']);
    fputcsv($output, ['Bank Account Number: 0023821']);
    fputcsv($output, ['Transit : 02091, Bank 006']);
    fputcsv($output, ['BIC-Swift: BNDCCAMMINT']);

    // Daily details with gate columns
    fputcsv($output, []);
    fputcsv($output, []);
    fputcsv($output, ['STATION: YYZ']);
    fputcsv($output, ['Customer: ' . $displayAirline]);
    fputcsv($output, []);
    fputcsv($output, ['Date', 'FLT IN', 'FLT OUT', 'Aircraft Reg', 'Arrival Gate', 'Departure Gate', 'ATA', 'ATD', 'Off Schedule', 'Engine Oil Qty', 'Tires Serviced', 'Hydraulic Qty', 'Comments']);
    foreach ($records as $rec) {
        $oil = $rec['engine_oil1_qty'] + $rec['engine_oil2_qty'] + $rec['apu_oil_qty'];
        fputcsv($output, [
            date('n/j/Y', strtotime($rec['arrival_datetime'])),
            $rec['inbound_flight'],
            $rec['outbound_flight'],
            $rec['registration'],
            $rec['arrival_gate'] ?? '',
            $rec['departure_gate'] ?? '',
            date('Hi', strtotime($rec['arrival_datetime'])),
            date('Hi', strtotime($rec['departure_datetime'])),
            (isset($rec['off_schedule']) && $rec['off_schedule'] == 'yes') ? 'Yes' : 'No',
            $oil,
            $rec['tires_serviced'],
            $rec['hydraulic_qty'],
            $rec['comments']
        ]);
    }
    fclose($output);
    exit;
}

// -------------------------------
// Export Daily Hours Report to Excel
// -------------------------------
function exportDailyHoursToExcel($dailyHours, $month, $year) {
    $filename = 'Daily_Engineer_Hours_' . $year . '_' . str_pad($month, 2, '0', STR_PAD_LEFT) . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    $output = fopen('php://output', 'w');
    
    // Header
    fputcsv($output, ['Daily Engineer Hours Report']);
    fputcsv($output, ['Period: ' . date('F Y', mktime(0,0,0,$month,1,$year))]);
    fputcsv($output, []);
    fputcsv($output, ['Airline', 'Date', 'Total Engineer Hours']);
    
    $grandTotal = 0;
    foreach ($dailyHours as $airline => $dates) {
        $airlineTotal = 0;
        foreach ($dates as $date => $hours) {
            $airlineTotal += $hours;
            $grandTotal += $hours;
            fputcsv($output, [
                $airline,
                date('M d, Y', strtotime($date)),
                number_format($hours, 2) . ' hrs'
            ]);
        }
        // Airline subtotal
        fputcsv($output, [$airline . ' - Monthly Total', '', number_format($airlineTotal, 2) . ' hrs']);
        fputcsv($output, []); // blank line separator
    }
    
    // Grand total
    fputcsv($output, ['GRAND TOTAL', '', number_format($grandTotal, 2) . ' hrs']);
    
    fclose($output);
    exit;
}
?>