<?php
include 'admin-header.php';
require_once '../includes/image-resizer.php';

$message = '';
// --- ACTION HANDLING: ADD/EDIT/DELETE FERRY ROUTES ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- DELETE ROUTE ---
    if (isset($_POST['delete_route'])) {
        $id_to_delete = intval($_POST['id']);
        $stmt_img = $conn->prepare("SELECT main_image_url FROM ferry_routes WHERE id = ?");
        $stmt_img->bind_param("i", $id_to_delete);
        $stmt_img->execute();
        if ($row_img = $stmt_img->get_result()->fetch_assoc()) {
            if (!empty($row_img['main_image_url']) && file_exists('../' . $row_img['main_image_url'])) {
                unlink('../' . $row_img['main_image_url']);
            }
        }
        $stmt = $conn->prepare("DELETE FROM ferry_routes WHERE id = ?");
        $stmt->bind_param("i", $id_to_delete);
        $stmt->execute();
        $message = '<div class="alert alert-success">Ferry route deleted successfully.</div>';
    } 
    // --- SAVE (ADD/EDIT) ROUTE ---
    elseif (isset($_POST['save_route'])) {
        $id = intval($_POST['id'] ?? 0);
        $origin_port_id = intval($_POST['origin_port_id']);
        $destination_port_id = intval($_POST['destination_port_id']);
        $ferry_company = trim($_POST['ferry_company']);
        $description = trim($_POST['description']);
        $main_image_url = $_POST['current_image_url'] ?? '';

        if (isset($_FILES['main_image']) && $_FILES['main_image']['error'] == 0) {
            $target_dir = "../uploads/ferries/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
            $target_file = $target_dir . "ferry-" . uniqid() . basename($_FILES["main_image"]["name"]);
            if (resizeImage($_FILES["main_image"]["tmp_name"], $target_file, 1200, 800)) {
                $main_image_url = str_replace('../', '', $target_file);
            }
        }

        if ($id > 0) { // Update
            $stmt = $conn->prepare("UPDATE ferry_routes SET origin_port_id=?, destination_port_id=?, ferry_company=?, description=?, main_image_url=? WHERE id=?");
            $stmt->bind_param("iisssi", $origin_port_id, $destination_port_id, $ferry_company, $description, $main_image_url, $id);
            $message = '<div class="alert alert-success">Ferry route updated successfully.</div>';
        } else { // Insert
            $stmt = $conn->prepare("INSERT INTO ferry_routes (origin_port_id, destination_port_id, ferry_company, description, main_image_url) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("iisss", $origin_port_id, $destination_port_id, $ferry_company, $description, $main_image_url);
            $message = '<div class="alert alert-success">New ferry route added successfully.</div>';
        }
        $stmt->execute();
        $stmt->close();
    }
}

// Fetch all ports for dropdown menus
$ports_result = $conn->query("SELECT * FROM ferry_ports ORDER BY city, port_name");
$ports = $ports_result->fetch_all(MYSQLI_ASSOC);

// Fetch route for editing if an ID is provided
$edit_route = null;
if (isset($_GET['edit'])) {
    $stmt = $conn->prepare("SELECT * FROM ferry_routes WHERE id = ?");
    $stmt->bind_param("i", $_GET['edit']);
    $stmt->execute();
    $edit_route = $stmt->get_result()->fetch_assoc();
}
?>

<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 Ferry Routes</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm mb-4">
    <div class="card-header fw-bold"><?php echo $edit_route ? 'Edit Ferry Route' : 'Add New Ferry Route'; ?></div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?php echo $edit_route['id'] ?? 0; ?>">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Origin Port</label>
                    <select name="origin_port_id" class="form-select" required>
                        <option value="">-- Select Origin --</option>
                        <?php foreach($ports as $port): ?>
                        <option value="<?php echo $port['id']; ?>" <?php if(isset($edit_route['origin_port_id']) && $edit_route['origin_port_id'] == $port['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($port['city'] . ' - ' . $port['port_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Destination Port</label>
                    <select name="destination_port_id" class="form-select" required>
                        <option value="">-- Select Destination --</option>
                        <?php foreach($ports as $port): ?>
                        <option value="<?php echo $port['id']; ?>" <?php if(isset($edit_route['destination_port_id']) && $edit_route['destination_port_id'] == $port['id']) echo 'selected'; ?>>
                             <?php echo htmlspecialchars($port['city'] . ' - ' . $port['port_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="mb-3"><label>Ferry Company</label><input type="text" class="form-control" name="ferry_company" value="<?php echo htmlspecialchars($edit_route['ferry_company'] ?? ''); ?>" placeholder="e.g., 2GO Travel, OceanJet" required></div>
            <div class="mb-3"><label>Description</label><textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars($edit_route['description'] ?? ''); ?></textarea></div>
            <div class="mb-3">
                <label>Route Image</label><input type="file" class="form-control" name="main_image" accept="image/*">
                <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($edit_route['main_image_url'] ?? ''); ?>">
                <?php if (!empty($edit_route['main_image_url'])): ?><div class="mt-2"><small>Current:</small><br><img src="../<?php echo htmlspecialchars($edit_route['main_image_url']); ?>" style="max-height: 80px;" class="img-thumbnail"></div><?php endif; ?>
            </div>
            <button type="submit" name="save_route" class="btn btn-primary"><?php echo $edit_route ? 'Save Changes' : 'Add Route'; ?></button>
            <?php if ($edit_route): ?><a href="manage-ferry-routes.php" class="btn btn-secondary">Cancel Edit</a><?php endif; ?>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header fw-bold">Existing Ferry Routes</div>
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-dark"><tr><th>Route</th><th>Company</th><th>Actions</th></tr></thead>
            <tbody>
                <?php
                $sql = "SELECT fr.*, orig.city as origin_city, dest.city as dest_city 
                        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
                        ORDER BY orig.city, dest.city ASC";
                $result = $conn->query($sql);
                while ($route = $result->fetch_assoc()):
                ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($route['origin_city']); ?> → <?php echo htmlspecialchars($route['dest_city']); ?></strong></td>
                    <td><?php echo htmlspecialchars($route['ferry_company']); ?></td>
                    <td>
                        <div class="btn-group">
                            <a href="?edit=<?php echo $route['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure?');">
                                <input type="hidden" name="id" value="<?php echo $route['id']; ?>">
                                <button type="submit" name="delete_route" class="btn btn-sm btn-danger">Delete</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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