<?php
include 'auth.php';
include '../includes/header.php';

// Self-healing migrations
$check_sort = $conn->query("SHOW COLUMNS FROM packages LIKE 'sort_order'");
if ($check_sort && $check_sort->num_rows == 0) {
    $conn->query("ALTER TABLE packages ADD COLUMN sort_order INT DEFAULT 0");
}
$check_type = $conn->query("SHOW COLUMNS FROM packages LIKE 'tour_type'");
if ($check_type && $check_type->num_rows == 0) {
    $conn->query("ALTER TABLE packages ADD COLUMN tour_type VARCHAR(20) DEFAULT 'group'");
}

// Handle Delete
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    $conn->query("DELETE FROM packages WHERE id = $del_id");
    header("Location: packages.php");
    exit();
}

// Handle Order Update
if (isset($_POST['update_order'])) {
    if (isset($_POST['sort_order']) && is_array($_POST['sort_order'])) {
        foreach ($_POST['sort_order'] as $pkg_id => $order_val) {
            $pkg_id = (int)$pkg_id;
            $order_val = (int)$order_val;
            $conn->query("UPDATE packages SET sort_order = $order_val WHERE id = $pkg_id");
        }
        $_SESSION['success_msg'] = "Tour order updated successfully!";
        header("Location: packages.php");
        exit();
    }
}

$packages = $conn->query("SELECT p.*, d.name as country_name FROM packages p JOIN destinations d ON p.country_id = d.id ORDER BY p.sort_order DESC, p.id DESC");
?>

<div class="container-fluid py-4">
    <form method="POST" action="packages.php">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="fw-bold mb-0">Manage International Tours</h2>
            <div class="d-flex gap-2">
                <button type="submit" name="update_order" class="btn btn-success rounded-pill px-4 shadow-sm">
                    <i class="fas fa-save me-2"></i> Save Order
                </button>
                <a href="add-package.php" class="btn btn-primary rounded-pill px-4 shadow-sm">
                    <i class="fas fa-plus me-2"></i> Add New Package
                </a>
            </div>
        </div>

        <?php if (isset($_SESSION['success_msg'])): ?>
            <div class="alert alert-success border-0 shadow-sm mb-4" style="border-radius: 15px; background-color: #d1e7dd; color: #0f5132; padding: 15px 20px;">
                <i class="fas fa-check-circle me-2"></i> <?= $_SESSION['success_msg'] ?>
            </div>
            <?php unset($_SESSION['success_msg']); ?>
        <?php endif; ?>

        <div class="card border-0 shadow-sm" style="border-radius: 20px;">
            <div class="card-body p-4">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Cover</th>
                                <th>Tour Title</th>
                                <th>Destination</th>
                                <th>Type</th>
                                <th>Duration</th>
                                <th>Price</th>
                                <th style="width: 120px;">Order No.</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($packages && $packages->num_rows > 0): ?>
                                <?php while($p = $packages->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <?php if($p['main_image']): ?>
                                                <img src="../uploads/<?= $p['main_image'] ?>" height="50" class="rounded">
                                            <?php else: ?>
                                                <div class="bg-light rounded text-center d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                                                    <i class="fas fa-image text-muted"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="fw-bold"><?= htmlspecialchars($p['title']) ?></span></td>
                                        <td><span class="badge bg-info text-white"><?= htmlspecialchars($p['country_name']) ?></span></td>
                                        <td>
                                            <?php $type = $p['tour_type'] ?? 'group'; ?>
                                            <span class="badge <?= $type === 'private' ? 'bg-warning text-dark' : 'bg-success' ?>"><?= ucfirst($type) ?> Tour</span>
                                        </td>
                                        <td><span class="small text-muted"><?= htmlspecialchars($p['duration']) ?></span></td>
                                        <td><span class="text-primary fw-bold">LKR <?= number_format($p['price'], 0) ?></span></td>
                                        <td>
                                            <input type="number" name="sort_order[<?= $p['id'] ?>]" value="<?= htmlspecialchars($p['sort_order'] ?? 0) ?>" class="form-control form-control-sm text-center fw-bold" style="border-radius: 8px;">
                                        </td>
                                        <td class="text-end">
                                            <div class="btn-group shadow-sm" style="border-radius: 10px; overflow: hidden;">
                                                <a href="edit-package.php?id=<?= $p['id'] ?>" class="btn btn-light btn-sm px-3">
                                                    <i class="fas fa-edit text-primary"></i>
                                                </a>
                                                <a href="packages.php?delete=<?= $p['id'] ?>" class="btn btn-light btn-sm px-3" onclick="return confirm('Are you sure?')">
                                                    <i class="fas fa-trash text-danger"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="8" class="text-center py-5">
                                        <p class="mt-3 text-muted">No tour packages found. Click "Add New Package" to get started.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </form>
</div>

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