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

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

// 2. HANDLE FORM SUBMISSIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    switch ($action) {
        case 'add_route':
            $origin_port_id = filter_input(INPUT_POST, 'origin_port_id', FILTER_VALIDATE_INT);
            $destination_port_id = filter_input(INPUT_POST, 'destination_port_id', FILTER_VALIDATE_INT);
            $ferry_company = trim($_POST['ferry_company']);
            $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
            $create_return = isset($_POST['create_return_route']);

            if ($origin_port_id && $destination_port_id && !empty($ferry_company) && $price !== false) {
                $conn->begin_transaction();
                try {
                    // Insert the primary route
                    $stmt = $conn->prepare("INSERT INTO ferry_routes (origin_port_id, destination_port_id, ferry_company, price) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("iisd", $origin_port_id, $destination_port_id, $ferry_company, $price);
                    $stmt->execute();
                    
                    // NEW: Handle return route creation
                    if ($create_return) {
                        // Swap origin and destination for the return trip
                        $stmt->bind_param("iisd", $destination_port_id, $origin_port_id, $ferry_company, $price);
                        $stmt->execute();
                    }
                    
                    $conn->commit();
                    $_SESSION['success_message'] = "Ferry route(s) added successfully.";
                } catch (mysqli_sql_exception $exception) {
                    $conn->rollback();
                    $_SESSION['error_message'] = "An error occurred: " . $exception->getMessage();
                }
                $stmt->close();
            } else { $_SESSION['error_message'] = "All fields are required."; }
            break;

        case 'edit_route':
            // (Standard edit logic remains the same)
            $route_id = filter_input(INPUT_POST, 'route_id', FILTER_VALIDATE_INT);
            $origin_port_id = filter_input(INPUT_POST, 'origin_port_id', FILTER_VALIDATE_INT);
            $destination_port_id = filter_input(INPUT_POST, 'destination_port_id', FILTER_VALIDATE_INT);
            $ferry_company = trim($_POST['ferry_company']);
            $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
            if ($route_id && $origin_port_id && $destination_port_id && !empty($ferry_company) && $price !== false) {
                $stmt = $conn->prepare("UPDATE ferry_routes SET origin_port_id = ?, destination_port_id = ?, ferry_company = ?, price = ? WHERE id = ?");
                $stmt->bind_param("iisdi", $origin_port_id, $destination_port_id, $ferry_company, $price, $route_id);
                if ($stmt->execute()) $_SESSION['success_message'] = "Ferry route updated successfully."; else $_SESSION['error_message'] = "Error updating route.";
                $stmt->close();
            } else { $_SESSION['error_message'] = "Invalid data for update."; }
            break;

        case 'delete_route':
            $route_id = filter_input(INPUT_POST, 'route_id', FILTER_VALIDATE_INT);
            if ($route_id) {
                $stmt = $conn->prepare("DELETE FROM ferry_routes WHERE id = ?");
                $stmt->bind_param("i", $route_id);
                if ($stmt->execute()) $_SESSION['success_message'] = "Ferry route deleted successfully."; else $_SESSION['error_message'] = "Error deleting route.";
                $stmt->close();
            }
            break;
    }
    header("Location: manage-ferry-routes.php");
    exit();
}

// 3. FETCH DATA FOR DISPLAY AND MODALS
$all_ports_result = $conn->query("SELECT id, name, location FROM ferry_ports ORDER BY location ASC, name ASC");
$all_ports = $all_ports_result->fetch_all(MYSQLI_ASSOC);

// Pagination & Search logic
$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)) {
    $where_clauses[] = "(orig.location LIKE ? OR dest.location LIKE ? OR fr.ferry_company 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) : '';

$base_query = "FROM ferry_routes fr JOIN ferry_ports orig ON fr.origin_port_id = orig.id JOIN ferry_ports dest ON fr.destination_port_id = dest.id $where_sql";
$count_sql = "SELECT COUNT(fr.id) as total $base_query";
$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_sql = "SELECT fr.*, orig.name as origin_name, orig.location as origin_location, dest.name as destination_name, dest.location as destination_location
              $base_query ORDER BY origin_location ASC, destination_location 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();
$routes_result = $stmt_fetch->get_result();

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

<div class="card shadow-sm">
    <div class="card-header"><i class="bi bi-search me-1"></i> Search Routes</div>
    <div class="card-body">
        <form action="manage-ferry-routes.php" method="GET" class="row g-3">
            <div class="col-md-9"><input type="text" name="search" class="form-control" placeholder="Search by Location or Ferry Company..." 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-ferry-routes.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
    <div class="table-responsive">
        <table class="table table-striped table-hover mb-0">
            <thead class="table-dark align-middle">
                <tr><th>Route</th><th>Ferry Company</th><th>Price</th><th class="text-end">Actions</th></tr>
            </thead>
            <tbody>
                <?php if ($routes_result->num_rows > 0): while ($route = $routes_result->fetch_assoc()): ?>
                <tr>
                    <td>
                        <div class="fw-bold"><?php echo htmlspecialchars($route['origin_location']); ?></div>
                        <div class="text-muted"><i class="bi bi-arrow-right"></i> <?php echo htmlspecialchars($route['destination_location']); ?></div>
                    </td>
                    <td><?php echo htmlspecialchars($route['ferry_company']); ?></td>
                    <td>₱<?php echo number_format($route['price'], 2); ?></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="#routeModal"
                                    data-id="<?php echo $route['id']; ?>" data-origin-id="<?php echo $route['origin_port_id']; ?>"
                                    data-destination-id="<?php echo $route['destination_port_id']; ?>" data-company="<?php echo htmlspecialchars($route['ferry_company']); ?>"
                                    data-price="<?php echo $route['price']; ?>"><i class="bi bi-pencil-fill"></i></button>
                            <form method="POST" action="manage-ferry-routes.php" onsubmit="return confirm('Are you sure?');"><input type="hidden" name="action" value="delete_route"><input type="hidden" name="route_id" value="<?php echo $route['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="4" class="text-center p-4">No ferry routes found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="modal fade" id="routeModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form action="manage-ferry-routes.php" method="POST"><div class="modal-header"><h5 class="modal-title" id="routeModalLabel">Add New Route</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_route"><input type="hidden" name="route_id" id="modal-route-id">
    <div class="mb-3"><label for="modal-origin" class="form-label">Origin Port <span class="text-danger">*</span></label><select class="form-select" id="modal-origin" name="origin_port_id" required><option value="" disabled selected>Select origin...</option><?php foreach ($all_ports as $port) echo "<option value='{$port['id']}'>" . htmlspecialchars($port['location'] . " (" . $port['name'] . ")") . "</option>"; ?></select></div>
    <div class="mb-3"><label for="modal-destination" class="form-label">Destination Port <span class="text-danger">*</span></label><select class="form-select" id="modal-destination" name="destination_port_id" required><option value="" disabled selected>Select destination...</option><?php foreach ($all_ports as $port) echo "<option value='{$port['id']}'>" . htmlspecialchars($port['location'] . " (" . $port['name'] . ")") . "</option>"; ?></select></div>
    <div class="mb-3"><label for="modal-company" class="form-label">Ferry Company <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-company" name="ferry_company" required></div>
    <div class="mb-3"><label for="modal-price" class="form-label">Price <span class="text-danger">*</span></label><div class="input-group"><span class="input-group-text">₱</span><input type="number" step="0.01" class="form-control" id="modal-price" name="price" required></div></div>
    <div class="form-check" id="return-route-wrapper"><input class="form-check-input" type="checkbox" id="create_return_route" name="create_return_route" checked><label class="form-check-label" for="create_return_route">Create return route automatically</label></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 Route</button></div></form></div></div></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const routeModal = document.getElementById('routeModal');
    const returnRouteWrapper = document.getElementById('return-route-wrapper');
    routeModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget; const form = routeModal.querySelector('form'); form.reset();
        if (button.classList.contains('edit-btn')) {
            routeModal.querySelector('.modal-title').textContent = 'Edit Route';
            routeModal.querySelector('#modal-submit-btn').textContent = 'Update Route';
            document.getElementById('modal-action').value = 'edit_route';
            document.getElementById('modal-route-id').value = button.dataset.id;
            document.getElementById('modal-origin').value = button.dataset.originId;
            document.getElementById('modal-destination').value = button.dataset.destinationId;
            document.getElementById('modal-company').value = button.dataset.company;
            document.getElementById('modal-price').value = button.dataset.price;
            returnRouteWrapper.style.display = 'none'; // Hide checkbox on edit
        } else {
            routeModal.querySelector('.modal-title').textContent = 'Add New Route';
            routeModal.querySelector('#modal-submit-btn').textContent = 'Save Route';
            document.getElementById('modal-action').value = 'add_route';
            document.getElementById('modal-route-id').value = '';
            returnRouteWrapper.style.display = 'block'; // Show checkbox on add
        }
    });
});
</script>

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