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

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

// 2. HANDLE FORM SUBMISSIONS (CREATE, UPDATE, DELETE, BULK ADD)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    switch ($action) {
        case 'add_port':
            $port_name = trim($_POST['name']); // `name` from your schema
            $location = trim($_POST['location']);
            if (!empty($port_name) && !empty($location)) {
                $stmt = $conn->prepare("INSERT INTO ferry_ports (name, location) VALUES (?, ?)");
                $stmt->bind_param("ss", $port_name, $location);
                if ($stmt->execute()) {
                    $_SESSION['success_message'] = "Ferry port added successfully.";
                } else {
                    $_SESSION['error_message'] = "Error: " . $stmt->error;
                }
                $stmt->close();
            } else { $_SESSION['error_message'] = "Port Name and Location are required."; }
            break;

        case 'edit_port':
            $port_id = filter_input(INPUT_POST, 'port_id', FILTER_VALIDATE_INT);
            $port_name = trim($_POST['name']);
            $location = trim($_POST['location']);
            if ($port_id && !empty($port_name) && !empty($location)) {
                $stmt = $conn->prepare("UPDATE ferry_ports SET name = ?, location = ? WHERE id = ?");
                $stmt->bind_param("ssi", $port_name, $location, $port_id);
                if ($stmt->execute()) {
                    $_SESSION['success_message'] = "Ferry port updated successfully.";
                } else {
                    $_SESSION['error_message'] = "Error: " . $stmt->error;
                }
                $stmt->close();
            } else { $_SESSION['error_message'] = "Invalid data for update."; }
            break;

        case 'delete_port':
            $port_id = filter_input(INPUT_POST, 'port_id', FILTER_VALIDATE_INT);
            if ($port_id) {
                $stmt = $conn->prepare("DELETE FROM ferry_ports WHERE id = ?");
                $stmt->bind_param("i", $port_id);
                if ($stmt->execute()) {
                    $_SESSION['success_message'] = "Ferry port deleted successfully.";
                } else {
                    $_SESSION['error_message'] = "Error deleting port. It might be in use on a route.";
                }
                $stmt->close();
            }
            break;
            
        case 'bulk_add_ports':
            $bulk_data = trim($_POST['bulk_data']);
            $lines = explode("\n", $bulk_data);
            $success_count = 0; $error_count = 0;
            $conn->begin_transaction();
            try {
                $stmt = $conn->prepare("INSERT INTO ferry_ports (name, location) VALUES (?, ?)");
                foreach ($lines as $line) {
                    $line = trim($line);
                    if (empty($line)) continue;
                    $parts = array_map('trim', explode(',', $line));
                    if (count($parts) === 2) {
                        $stmt->bind_param("ss", $parts[0], $parts[1]);
                        $stmt->execute();
                        $success_count++;
                    } else { $error_count++; }
                }
                $stmt->close();
                $conn->commit();
                $_SESSION['success_message'] = "Bulk add complete. Added: $success_count. Skipped invalid lines: $error_count.";
            } catch (mysqli_sql_exception $exception) {
                $conn->rollback();
                $_SESSION['error_message'] = "An error occurred during bulk add. No ports were added.";
            }
            break;
    }
    
    header("Location: manage-ferry-ports.php");
    exit();
}

// 3. FETCH PORTS 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)) {
    $where_clauses[] = "(name LIKE ? OR location LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term);
    $types .= 'ss';
}
$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

$count_sql = "SELECT COUNT(id) as total FROM ferry_ports $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_sql = "SELECT * FROM ferry_ports $where_sql ORDER BY 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();
$ports_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 Ferry Ports</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <button type="button" class="btn btn-outline-secondary me-2" data-bs-toggle="modal" data-bs-target="#bulkAddModal">
            <i class="bi bi-upload me-1"></i> Bulk Add
        </button>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#portModal">
            <i class="bi bi-plus-circle-fill me-1"></i> Add New Port
        </button>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header"><i class="bi bi-search me-1"></i> Search Ports</div>
    <div class="card-body">
        <form action="manage-ferry-ports.php" method="GET" class="row g-3">
            <div class="col-md-9"><input type="text" name="search" class="form-control" placeholder="Search by Port Name or Location..." 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-ports.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>Port Name (ID)</th><th>Location</th><th class="text-end">Actions</th></tr>
            </thead>
            <tbody>
                <?php if ($ports_result->num_rows > 0): while ($port = $ports_result->fetch_assoc()): ?>
                <tr>
                    <td>
                        <strong class="d-block"><?php echo htmlspecialchars($port['name']); ?></strong>
                        <small class="text-muted">ID: <?php echo $port['id']; ?></small>
                    </td>
                    <td><?php echo htmlspecialchars($port['location']); ?></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="#portModal"
                                    data-id="<?php echo $port['id']; ?>" data-name="<?php echo htmlspecialchars($port['name']); ?>"
                                    data-location="<?php echo htmlspecialchars($port['location']); ?>">
                                <i class="bi bi-pencil-fill"></i>
                            </button>
                            <form method="POST" action="manage-ferry-ports.php" onsubmit="return confirm('Are you sure you want to delete this port?');">
                                <input type="hidden" name="action" value="delete_port"><input type="hidden" name="port_id" value="<?php echo $port['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="3" class="text-center p-4">No ferry ports found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</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="portModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form action="manage-ferry-ports.php" method="POST"><div class="modal-header"><h5 class="modal-title" id="portModalLabel">Add New Port</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_port"><input type="hidden" name="port_id" id="modal-port-id">
<div class="mb-3"><label for="modal-name" class="form-label">Port Name <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-name" name="name" required></div>
<div class="mb-3"><label for="modal-location" class="form-label">Location (City) <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-location" name="location" required></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 Port</button></div></form></div></div></div>

<div class="modal fade" id="bulkAddModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form action="manage-ferry-ports.php" method="POST"><div class="modal-header"><h5 class="modal-title">Bulk Add Ports</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body"><input type="hidden" name="action" value="bulk_add_ports">
<div class="alert alert-info small"><i class="bi bi-info-circle-fill me-2"></i>Enter one port per line in the format: <strong>Port Name, Location</strong></div>
<textarea name="bulk_data" class="form-control font-monospace" rows="10" placeholder="Manila North Harbor, Manila&#10;Cebu City Pier 1, Cebu City"></textarea></div>
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Add Ports</button></div></form></div></div></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const portModal = document.getElementById('portModal');
    portModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const form = portModal.querySelector('form'); form.reset();
        if (button.classList.contains('edit-btn')) {
            portModal.querySelector('.modal-title').textContent = 'Edit Port';
            portModal.querySelector('#modal-submit-btn').textContent = 'Update Port';
            document.getElementById('modal-action').value = 'edit_port';
            document.getElementById('modal-port-id').value = button.dataset.id;
            document.getElementById('modal-name').value = button.dataset.name;
            document.getElementById('modal-location').value = button.dataset.location;
        } else {
            portModal.querySelector('.modal-title').textContent = 'Add New Port';
            portModal.querySelector('#modal-submit-btn').textContent = 'Save Port';
            document.getElementById('modal-action').value = 'add_port';
            document.getElementById('modal-port-id').value = '';
        }
    });
});
</script>

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