<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// --- Page-Specific Logic Starts Here ---

// 2. HANDLE FORM SUBMISSIONS (CREATE, UPDATE, DELETE)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    // --- ADD NEW AIRPORT ---
    if ($action === 'add_airport') {
        $airport_name = trim($_POST['airport_name']);
        $code = strtoupper(trim($_POST['airport_code']));
        $city = trim($_POST['name']); // In your schema, 'name' is the city
        $country = trim($_POST['country']);

        if (!empty($airport_name) && !empty($code) && !empty($city)) {
            $stmt = $conn->prepare("INSERT INTO airports (airport_name, airport_code, name, country) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $airport_name, $code, $city, $country);
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Airport added successfully.";
            } else {
                $_SESSION['error_message'] = "Error adding airport: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $_SESSION['error_message'] = "Airport Name, Code, and City are required.";
        }
    }

    // --- UPDATE EXISTING AIRPORT ---
    if ($action === 'edit_airport') {
        $airport_id = filter_input(INPUT_POST, 'airport_id', FILTER_VALIDATE_INT);
        $airport_name = trim($_POST['airport_name']);
        $code = strtoupper(trim($_POST['airport_code']));
        $city = trim($_POST['name']); // 'name' is the city
        $country = trim($_POST['country']);

        if ($airport_id && !empty($airport_name) && !empty($code) && !empty($city)) {
            $stmt = $conn->prepare("UPDATE airports SET airport_name = ?, airport_code = ?, name = ?, country = ? WHERE id = ?");
            $stmt->bind_param("ssssi", $airport_name, $code, $city, $country, $airport_id);
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Airport updated successfully.";
            } else {
                $_SESSION['error_message'] = "Error updating airport: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $_SESSION['error_message'] = "Invalid data provided for update.";
        }
    }

    // --- DELETE AIRPORT ---
    if ($action === 'delete_airport') {
        $airport_id = filter_input(INPUT_POST, 'airport_id', FILTER_VALIDATE_INT);
        if ($airport_id) {
            $stmt = $conn->prepare("DELETE FROM airports WHERE id = ?");
            $stmt->bind_param("i", $airport_id);
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Airport deleted successfully.";
            } else {
                $_SESSION['error_message'] = "Error deleting airport. It might be in use in a flight booking.";
            }
            $stmt->close();
        }
    }
    
    header("Location: manage-airports.php");
    exit();
}


// 3. FETCH AIRPORTS FOR DISPLAY
$records_per_page = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$where_clauses = []; $params = []; $types = '';
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    // Corrected to search airport_name, airport_code, and name (city)
    $where_clauses[] = "(airport_name LIKE ? OR airport_code LIKE ? OR name LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term, $like_term);
    $types .= 'sss';
}
$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

// Count for pagination
$count_sql = "SELECT COUNT(id) as total FROM airports $where_sql";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

// Fetch for display
$fetch_sql = "SELECT * FROM airports $where_sql ORDER BY airport_name ASC LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$airports_result = $stmt_fetch->get_result();


// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Airports</h1>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#airportModal">
        <i class="bi bi-plus-circle-fill me-1"></i> Add New Airport
    </button>
</div>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-search me-1"></i> Search Airports</div>
    <div class="card-body">
        <form action="manage-airports.php" method="GET" class="row g-3">
            <div class="col-md-9"><input type="text" name="search" class="form-control" placeholder="Search by Name, IATA Code, or City..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-md-3 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Search</button><a href="manage-airports.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover">
        <thead class="table-dark align-middle">
            <tr>
                <th>Airport Name</th>
                <th class="text-center">IATA Code</th>
                <th>City</th>
                <th>Country</th>
                <th class="text-end">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($airports_result->num_rows > 0): while ($airport = $airports_result->fetch_assoc()): ?>
            <tr>
                <td class="fw-bold"><?php echo htmlspecialchars($airport['airport_name']); ?></td>
                <td class="text-center"><code><?php echo htmlspecialchars($airport['airport_code']); ?></code></td>
                <td><?php echo htmlspecialchars($airport['name']); // 'name' is the city ?></td>
                <td><?php echo htmlspecialchars($airport['country']); ?></td>
                <td class="text-end">
                    <div class="d-inline-flex gap-1">
                        <button type="button" class="btn btn-sm btn-warning edit-btn"
                                data-bs-toggle="modal" data-bs-target="#airportModal"
                                data-id="<?php echo $airport['id']; ?>"
                                data-airport-name="<?php echo htmlspecialchars($airport['airport_name']); ?>"
                                data-code="<?php echo htmlspecialchars($airport['airport_code']); ?>"
                                data-city="<?php echo htmlspecialchars($airport['name']); ?>"
                                data-country="<?php echo htmlspecialchars($airport['country']); ?>">
                            <i class="bi bi-pencil-fill"></i>
                        </button>
                        <form method="POST" action="manage-airports.php" onsubmit="return confirm('Are you sure you want to delete this airport?');">
                            <input type="hidden" name="action" value="delete_airport">
                            <input type="hidden" name="airport_id" value="<?php echo $airport['id']; ?>">
                            <button type="submit" class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i></button>
                        </form>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="5" class="text-center p-4">No airports found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<div class="modal fade" id="airportModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form action="manage-airports.php" method="POST">
        <div class="modal-header"><h5 class="modal-title" id="airportModalLabel">Add New Airport</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
            <input type="hidden" name="action" id="modal-action" value="add_airport">
            <input type="hidden" name="airport_id" id="modal-airport-id">
            <div class="mb-3"><label for="modal-airport-name" class="form-label">Airport Name <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-airport-name" name="airport_name" required></div>
            <div class="mb-3"><label for="modal-code" class="form-label">IATA Code (3 Letters) <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-code" name="airport_code" required maxlength="3" minlength="3"></div>
            <div class="mb-3"><label for="modal-city" class="form-label">City <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-city" name="name" required></div>
            <div class="mb-3"><label for="modal-country" class="form-label">Country</label><input type="text" class="form-control" id="modal-country" name="country"></div>
        </div>
        <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button type="submit" class="btn btn-primary" id="modal-submit-btn">Save Airport</button></div>
      </form>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const airportModal = document.getElementById('airportModal');
    airportModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const form = airportModal.querySelector('form'); form.reset();
        
        const modalTitle = airportModal.querySelector('.modal-title');
        const modalSubmitBtn = airportModal.querySelector('#modal-submit-btn');
        
        if (button.classList.contains('edit-btn')) {
            modalTitle.textContent = 'Edit Airport';
            modalSubmitBtn.textContent = 'Update Airport';
            document.getElementById('modal-action').value = 'edit_airport';
            document.getElementById('modal-airport-id').value = button.dataset.id;
            document.getElementById('modal-airport-name').value = button.dataset.airportName;
            document.getElementById('modal-code').value = button.dataset.code;
            document.getElementById('modal-city').value = button.dataset.city;
            document.getElementById('modal-country').value = button.dataset.country;
        } else {
            modalTitle.textContent = 'Add New Airport';
            modalSubmitBtn.textContent = 'Save Airport';
            document.getElementById('modal-action').value = 'add_airport';
            document.getElementById('modal-airport-id').value = '';
        }
    });
});
</script>

<?php include 'admin-footer.php'; ?>
