<?php
require_once 'config/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: auth/login.php");
    exit;
}

$lang_code = $_SESSION['language'] ?? 'english';
include "languages/$lang_code.php";

$result_text = "";

// تحميل بيانات المدن وشركات الطيران
$airports = json_decode(file_get_contents(__DIR__ . "/data/airports.json"), true);
$airlines = json_decode(file_get_contents(__DIR__ . "/data/airlines.json"), true);

// تنسيق الوقت بالعربية
function formatTimeArabic($time) {
    $hour = (int)substr($time, 0, 2);
    if ($hour >= 5 && $hour < 12) return "صباحًا";
    if ($hour >= 12 && $hour < 15) return "ظهرًا";
    if ($hour >= 15 && $hour < 18) return "عصرًا";
    if ($hour >= 18 && $hour < 24) return "مساءً";
    return "فجرًا";
}

// استرجاع اسم شركة الطيران حسب اللغة
function getAirlineName($code, $airlines, $lang_code) {
    foreach ($airlines as $a) {
        if (strtoupper($a['iata_code']) === strtoupper($code)) {
            return ($lang_code === 'arabic' && !empty($a['airline_name_ar']))
                ? $a['airline_name_ar']
                : $a['airline_name'];
        }
    }
    return $code;
}

// استرجاع اسم المدينة حسب اللغة
function getCityName($code, $airports, $lang_code) {
    foreach ($airports as $a) {
        if (strtoupper($a['iata_code']) === strtoupper($code)) {
            if ($lang_code === 'arabic' && !empty($a['city_ar'])) {
                return $a['city_ar'];
            }
            return $a['city'] ?: $a['airport_name'];
        }
    }
    return $code;
}

// حساب مدة الترانزيت
function calculateTransitTime($arrival, $departure) {
    $arr = DateTime::createFromFormat('H:i', $arrival);
    $dep = DateTime::createFromFormat('H:i', $departure);
    if ($dep < $arr) $dep->modify('+1 day');
    $diff = $arr->diff($dep);
    return [$diff->h, $diff->i];
}

// عند إرسال النموذج
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw_text = trim($_POST['raw_text'] ?? '');
    $created_by = $_SESSION['user_id'];

    if (!empty($raw_text)) {
        $lines = explode("\n", $raw_text);
        $output = "";
        $count = 1;
        $previous_arrival = null;

        foreach ($lines as $line) {
            $line = preg_replace('/^\s*\d+\s*[\.\-\)]*\s*/', '', trim($line));
            $line = preg_replace('/[^A-Z0-9\s]/i', '', $line);
            $line = preg_replace('/([A-Z]{3})([A-Z]{3})/', '$1 $2', $line);
            $parts = preg_split('/\s+/', trim($line));
            if (count($parts) < 7) continue;

            $airline_code = strtoupper($parts[0]);
            $flight_no = $parts[1];
            $date_raw = $parts[2];
            $from = strtoupper($parts[3]);
            $to = strtoupper($parts[4]);
            $dep_raw = preg_replace('/[^0-9]/', '', $parts[5]);
            $arr_raw = preg_replace('/[^0-9]/', '', $parts[6] ?? '');

            if (strlen($dep_raw) < 4) $dep_raw = str_pad($dep_raw, 4, '0', STR_PAD_LEFT);
            if (strlen($arr_raw) < 4) $arr_raw = str_pad($arr_raw, 4, '0', STR_PAD_LEFT);

            $day = substr($date_raw, 0, 2);
            $month = strtoupper(substr($date_raw, 2, 3));
            $month_num = date('m', strtotime($month));

            $dep_time = substr($dep_raw, 0, 2) . ":" . substr($dep_raw, 2, 2);
            $arr_time = substr($arr_raw, 0, 2) . ":" . substr($arr_raw, 2, 2);

            $dep_datetime = DateTime::createFromFormat('H:i', $dep_time);
            $arr_datetime = DateTime::createFromFormat('H:i', $arr_time);

            $next_day_text = "";
            if ($arr_datetime < $dep_datetime) {
                $arr_datetime->modify('+1 day');
                $next_day_text = ($lang_code === 'arabic') ? " (اليوم التالي)" : " (next day)";
            }

            $airline_name = getAirlineName($airline_code, $airlines, $lang_code);
            $from_city = getCityName($from, $airports, $lang_code);
            $to_city = getCityName($to, $airports, $lang_code);

            // حساب الترانزيت إذا كانت الرحلة الحالية تتابع من السابقة
            $transit_text = "";
            if (!empty($previous_arrival) && $previous_arrival['to'] === $from) {
                list($h, $m) = calculateTransitTime($previous_arrival['arr_time'], $dep_time);
                if ($lang_code === 'arabic') {
                    $transit_text = " (مدة الترانزيت: {$h} ساعة و{$m} دقيقة)";
                } else {
                    $transit_text = " (Transit time: {$h}h {$m}m)";
                }
            }

            if ($lang_code === 'arabic') {
                $output .= "الرحلة رقم $count / $airline_name: ";
                $output .= "$from_city - $to_city بتاريخ $day / $month_num ";
                $output .= "رقم الرحلة ($airline_code $flight_no) ";
                $output .= "الإقلاع من $from_city الساعة $dep_time " . formatTimeArabic($dep_time);
                $output .= " والوصول إلى $to_city الساعة $arr_time " . formatTimeArabic($arr_time) . $next_day_text . $transit_text . "\n";
            } else {
                $output .= "Flight $count / Airline $airline_name: ";
                $output .= "$from_city - $to_city on $day/$month_num ";
                $output .= "Flight No. ($airline_code $flight_no). ";
                $output .= "Departure from $from_city at $dep_time and arrival to $to_city at $arr_time$next_day_text$transit_text.\n";
            }

            $previous_arrival = ['to' => $to, 'arr_time' => $arr_time];
            $count++;
        }

        $result_text = trim($output);

        if (!empty($result_text)) {
            date_default_timezone_set('Asia/Amman');
            $created_at = date('Y-m-d H:i:s');

            $stmt = $conn->prepare("INSERT INTO flight_details (raw_text, generated_text, created_by, created_at) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssis", $raw_text, $result_text, $created_by, $created_at);
            $stmt->execute();
        }
    }
}

include 'header.php';
?>

<div class="main-content p-4" style="flex:1;">
    <h2 class="mb-4"><?= $lang['flight_details_title'] ?></h2>

    <form method="POST" class="mb-4">
        <div class="mb-3">
            <label class="form-label fw-bold"><?= $lang['flight_details_input_label'] ?></label>
            <textarea name="raw_text" class="form-control" rows="5" placeholder="<?= $lang['flight_details_example'] ?>" required></textarea>
        </div>
        <button type="submit" class="btn btn-success"><?= $lang['flight_details_button'] ?></button>
    </form>

    <?php if (!empty($result_text)): ?>
        <h4><?= $lang['flight_details_result'] ?></h4>
        <div class="card">
            <div class="card-body">
                <textarea id="resultBox" rows="12" class="form-control"><?= htmlspecialchars($result_text) ?></textarea>
                <button class="btn btn-primary mt-2" onclick="copyText()"><?= $lang['flight_details_copy'] ?></button>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
function copyText() {
    var copyText = document.getElementById("resultBox");
    copyText.select();
    document.execCommand("copy");
    alert("<?= $lang['flight_details_copied'] ?>");
}
</script>

<?php include 'includes/footer.php'; ?>
