<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

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

// ضبط التوقيت إلى عمان
date_default_timezone_set('Asia/Amman');
$conn->query("SET time_zone = '+03:00'");

// إعداد البحث
$search = trim($_GET['search'] ?? '');
$where = ($user_id == 1) ? "WHERE 1" : "WHERE f.created_by = ?";
$params = [];
$types = "";

if (!empty($search)) {
    $where .= " AND (f.raw_text LIKE ? OR f.generated_text LIKE ?)";
    $search_like = "%$search%";
    if ($user_id == 1) {
        $params = [$search_like, $search_like];
        $types = "ss";
    } else {
        $params = [$user_id, $search_like, $search_like];
        $types = "iss";
    }
} else {
    if ($user_id != 1) {
        $params = [$user_id];
        $types = "i";
    }
}

// ترقيم الصفحات
$limit = 25;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

// حساب عدد السجلات
$count_sql = "SELECT COUNT(*) AS total FROM flight_details f $where";
$stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$total = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
$total_pages = ceil($total / $limit);
$stmt->close();

// جلب البيانات مع اسم المستخدم من الجدول users
$sql = "SELECT f.id, f.raw_text, f.generated_text, f.created_at, u.name AS created_by_name
        FROM flight_details f
        LEFT JOIN users u ON f.created_by = u.id
        $where
        ORDER BY f.id DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

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

    <form method="GET" class="mb-3">
        <div class="input-group">
            <input type="text" name="search" value="<?= htmlspecialchars($search) ?>"
                   class="form-control"
                   placeholder="<?= $lang['search_here'] ?>">
            <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i></button>
        </div>
    </form>

    <?php if ($result && $result->num_rows > 0): ?>
        <div class="table-responsive">
            <table class="table table-bordered table-striped align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>#</th>
                        <th><?= $lang['flight_details_input_label'] ?></th>
                        <th><?= $lang['flight_details_result'] ?></th>
                        <th><?= $lang['created_by'] ?></th>
                        <th><?= $lang['created_at'] ?></th>
                        <th><?= $lang['actions'] ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $i = $offset + 1;
                    while ($row = $result->fetch_assoc()):
                        $created_at_local = '';
                        if (!empty($row['created_at'])) {
                            $dt = new DateTime($row['created_at']);
                            $dt->setTimezone(new DateTimeZone('Asia/Amman'));
                            $created_at_local = $dt->format('Y-m-d H:i');
                        }
                    ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td style="white-space:pre-wrap;"><?= htmlspecialchars($row['raw_text']) ?></td>
                        <td style="white-space:pre-wrap;"><?= htmlspecialchars($row['generated_text']) ?></td>
                        <td><?= htmlspecialchars($row['created_by_name'] ?? '-') ?></td>
                        <td><?= htmlspecialchars($created_at_local) ?></td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="copyText('text<?= $row['id'] ?>')">
                                <i class="bi bi-clipboard"></i> <?= $lang['flight_details_copy'] ?>
                            </button>
                            <textarea id="text<?= $row['id'] ?>" class="d-none"><?= htmlspecialchars($row['generated_text']) ?></textarea>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

        <nav>
            <ul class="pagination justify-content-center">
                <?php if ($page > 1): ?>
                    <li class="page-item"><a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>">&laquo;</a></li>
                <?php endif; ?>

                <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                    <li class="page-item <?= $p == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $p ?>&search=<?= urlencode($search) ?>"><?= $p ?></a>
                    </li>
                <?php endfor; ?>

                <?php if ($page < $total_pages): ?>
                    <li class="page-item"><a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>">&raquo;</a></li>
                <?php endif; ?>
            </ul>
        </nav>
    <?php else: ?>
        <div class="alert alert-info"><?= $lang['no_records_found'] ?></div>
    <?php endif; ?>
</div>

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

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