<?php
require_once 'auth_check.php';
include 'sidebar.php';
require_once 'db.php';

if (!isset($conn) || !($conn instanceof mysqli)) {
    die('Database connection is not available.');
}

// Auto-Ensure Table & Columns Exist
$createTableQuery = "CREATE TABLE IF NOT EXISTS `packages` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `title` VARCHAR(255) NOT NULL,
    `slug` VARCHAR(255) DEFAULT NULL,
    `duration` VARCHAR(100) DEFAULT NULL,
    `price` VARCHAR(100) DEFAULT NULL,
    `description` TEXT DEFAULT NULL,
    `image` VARCHAR(255) DEFAULT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
mysqli_query($conn,$createTableQuery);

// Ensure missing columns exist
@mysqli_query($conn, "ALTER TABLE packages ADD COLUMN IF NOT EXISTS slug VARCHAR(255)");
@mysqli_query($conn, "ALTER TABLE packages ADD COLUMN IF NOT EXISTS duration VARCHAR(100)");
@mysqli_query($conn, "ALTER TABLE packages ADD COLUMN IF NOT EXISTS price VARCHAR(100)");
@mysqli_query($conn, "ALTER TABLE packages ADD COLUMN IF NOT EXISTS description TEXT");
@mysqli_query($conn, "ALTER TABLE packages ADD COLUMN IF NOT EXISTS image VARCHAR(255)");

$message = '';$error = '';

// Package Add Karne Ka Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_package'])) {$title = trim($_POST['title'] ?? '');$duration = trim($_POST['duration'] ?? '');$price = trim($_POST['price'] ?? '');$description = trim($_POST['description'] ?? '');$imagePath = '';

    // Image Upload Logic
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {$targetDir = "../uploads/packages/";
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        
        $fileExtension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $newFileName = time() . '_' . uniqid() . '.' . $fileExtension;
        $targetFile = $targetDir .$newFileName;

        if (move_uploaded_file($_FILES['image']['tmp_name'],$targetFile)) {
            $imagePath = 'uploads/packages/' .$newFileName;
        }
    }

    if (!empty($title)) {
        $slug_base = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-',$title)));
        $slug = rtrim($slug_base, '-') . '-' . time();

        $insert_sql = "INSERT INTO packages (title, slug, duration, price, description, image) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($conn,$insert_sql);
        
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "ssssss", $title,$slug, $duration,$price, $description,$imagePath);
            if (mysqli_stmt_execute($stmt)) {$message = "Package successfully add ho gaya!";
            } else {
                $error = "Execution Error: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            $error = "Prepare Error: " . mysqli_error($conn);
        }
    } else {
        $error = "Package ka title zaroori hai!";
    }
}

// Package Delete Karne Ka Logic
if (isset($_GET['delete_id'])) {$delete_id = intval($_GET['delete_id']);$delete_sql = "DELETE FROM packages WHERE id = ?";
    $stmt = mysqli_prepare($conn,$delete_sql);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $delete_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
        header("Location: manage-packages.php?msg=deleted");
        exit();
    }
}

// Packages Fetch Karein
$query = "SELECT * FROM packages ORDER BY id DESC";
$result = mysqli_query($conn,$query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Tour Packages | Wings Tour & Travels</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

    <style>
        :root {
            --brand-green: #12521f;
            --brand-saffron: #D4A359;
            --dark-navy: #0F172A;
            --sidebar-width: 260px;
            --bg-light: #F8FAFC;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg-light); display: flex; min-height: 100vh; }

        /* MAIN LAYOUT RESPONSIVE */
        .admin-main { 
            margin-left: var(--sidebar-width); 
            flex: 1; 
            display: flex; 
            flex-direction: column; 
            min-width: 0;
            transition: margin 0.3s ease;
        }

        .admin-topbar {
            background: #ffffff; 
            height: 70px; 
            padding: 0 30px;
            display: flex; 
            align-items: center; 
            justify-content: space-between;
            box-shadow: 0 2px 10px rgba(0,0,0,0.04); 
            position: sticky; 
            top: 0; 
            z-index: 99;
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* MOBILE NAV TOGGLE BUTTON */
        .mobile-nav-toggle {
            display: none;
            background: var(--dark-navy);
            color: #fff;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            align-items: center;
            justify-content: center;
            transition: background 0.2s;
        }
        .mobile-nav-toggle:hover {
            background: var(--brand-saffron);
            color: var(--dark-navy);
        }

        /* MOBILE OVERLAY BACKDROP */
        .sidebar-backdrop {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(15, 23, 42, 0.6);
            z-index: 99;
            backdrop-filter: blur(2px);
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .admin-content { padding: 30px; flex: 1; }
        .page-title { font-size: 22px; color: var(--dark-navy); margin-bottom: 20px; font-weight: 700; }

        .card {
            background: #ffffff; padding: 24px; border-radius: 14px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03); border: 1px solid #E2E8F0; margin-bottom: 30px;
        }

        .form-grid {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 18px; margin-bottom: 18px;
        }

        .form-group label {
            display: block; font-size: 13px; font-weight: 600; color: var(--dark-navy); margin-bottom: 6px;
        }

        .form-group input, .form-group textarea {
            width: 100%; padding: 11px 14px; border: 1px solid #CBD5E1; border-radius: 8px; font-size: 13.5px; outline: none; transition: border-color 0.2s;
        }
        .form-group input:focus, .form-group textarea:focus {
            border-color: var(--brand-saffron);
        }

        .btn-add {
            background: var(--brand-green); color: #ffffff; padding: 11px 22px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: opacity 0.2s;
        }
        .btn-add:hover { opacity: 0.9; }

        .table-container { background: #ffffff; border-radius: 14px; border: 1px solid #E2E8F0; overflow-x: auto; box-shadow: 0 4px 20px rgba(0,0,0,0.03); }
        table { width: 100%; border-collapse: collapse; text-align: left; font-size: 13.5px; white-space: nowrap; }
        th { background: #F8FAFC; color: var(--dark-navy); font-weight: 600; padding: 15px 20px; border-bottom: 1px solid #E2E8F0; }
        td { padding: 15px 20px; border-bottom: 1px solid #E2E8F0; color: #334155; vertical-align: middle; }

        .btn-delete {
            color: #EF4444; background: #FEF2F2; padding: 7px 12px; border-radius: 6px; text-decoration: none; font-size: 12px; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; transition: background 0.2s;
        }
        .btn-delete:hover { background: #FEE2E2; }

        .alert-success { padding: 14px 18px; background: #DCFCE7; color: #166534; border-radius: 10px; font-size: 13.5px; margin-bottom: 20px; border: 1px solid #BBF7D0; }
        .alert-error { padding: 14px 18px; background: #FEF2F2; color: #991B1B; border-radius: 10px; font-size: 13.5px; margin-bottom: 20px; border: 1px solid #FECACA; }
        .pkg-img-preview { width: 48px; height: 48px; object-fit: cover; border-radius: 8px; border: 1px solid #E2E8F0; }

        /* RESPONSIVE MEDIA QUERIES */
        @media (max-width: 992px) {
            .admin-main { margin-left: 0; }
            .mobile-nav-toggle { display: flex; }
            .sidebar-backdrop.show-backdrop { display: block; opacity: 1; }
            .admin-content { padding: 20px 15px; }
            .admin-topbar { padding: 0 15px; }
        }
    </style>
</head>
<body>

    <!-- Mobile Overlay Backdrop -->
    <div class="sidebar-backdrop" id="sidebarBackdrop" onclick="toggleSidebar()"></div>

    <div class="admin-main">
        <header class="admin-topbar">
            <div class="topbar-left">
                <!-- Mobile Menu Hamburger Trigger -->
                <button class="mobile-nav-toggle" onclick="toggleSidebar()" aria-label="Toggle Navigation">
                    <i class="fas fa-bars"></i>
                </button>
                <strong style="color: var(--dark-navy); font-size: 16px;">Tour Packages Management</strong>
            </div>
            <a href="login.php?action=logout" style="color: #EF4444; text-decoration: none; font-weight: 600; font-size: 13px; display: flex; align-items: center; gap: 6px;">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </header>

        <main class="admin-content">
            <h1 class="page-title">Manage Tour Packages</h1>

            <?php if (!empty($message) || (isset($_GET['msg']) &&$_GET['msg'] === 'deleted')): ?>
                <div class="alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo !empty($message) ?$message : 'Package successfully delete ho gaya!'; ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($error)): ?>
                <div class="alert-error">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <!-- ADD PACKAGE FORM -->
            <div class="card">
                <h3 style="margin-bottom: 18px; font-size: 16px; color: var(--dark-navy); font-weight: 600;">
                    <i class="fas fa-plus-circle" style="color: var(--brand-saffron);"></i> Add New Package
                </h3>
                <form action="manage-packages.php" method="POST" enctype="multipart/form-data">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Package Title</label>
                            <input type="text" name="title" placeholder="e.g. Kedarnath Dham Yatra" required>
                        </div>
                        <div class="form-group">
                            <label>Duration</label>
                            <input type="text" name="duration" placeholder="e.g. 5 Days / 4 Nights">
                        </div>
                        <div class="form-group">
                            <label>Price</label>
                            <input type="text" name="price" placeholder="e.g. ₹12,500 per person">
                        </div>
                        <div class="form-group">
                            <label>Package Image</label>
                            <input type="file" name="image" accept="image/*">
                        </div>
                    </div>
                    <div class="form-group" style="margin-bottom: 18px;">
                        <label>Description</label>
                        <textarea name="description" rows="3" placeholder="Package details & overview..."></textarea>
                    </div>
                    <button type="submit" name="add_package" class="btn-add"><i class="fas fa-plus"></i> Add Package</button>
                </form>
            </div>

            <!-- PACKAGES TABLE -->
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>#ID</th>
                            <th>Image</th>
                            <th>Title</th>
                            <th>Duration</th>
                            <th>Price</th>
                            <th>Description</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($result && mysqli_num_rows($result) > 0): ?>
                            <?php while ($row = mysqli_fetch_assoc($result)): ?>
                                <tr>
                                    <td><strong>#<?php echo $row['id']; ?></strong></td>
                                    <td>
                                        <?php if (!empty($row['image'])): ?>
                                            <img src="../<?php echo htmlspecialchars($row['image']); ?>" class="pkg-img-preview" alt="Package">
                                        <?php else: ?>
                                            <span style="color: #94A3B8; font-size: 11px;">No Image</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><strong><?php echo htmlspecialchars($row['title'] ?? ''); ?></strong></td>
                                    <td><?php echo htmlspecialchars($row['duration'] ?? 'N/A'); ?></td>
                                    <td><span style="color: var(--brand-green); font-weight: 600;"><?php echo htmlspecialchars($row['price'] ?? 'N/A'); ?></span></td>
                                    <td><?php echo htmlspecialchars($row['description'] ?? ''); ?></td>
                                    <td>
                                        <a href="manage-packages.php?delete_id=<?php echo $row['id']; ?>" class="btn-delete" onclick="return confirm('Is package ko delete karna chahte hain?');">
                                            <i class="fas fa-trash"></i> Delete
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" style="text-align: center; color: #94A3B8; padding: 30px;">Koi package nahi mila. Pehle add karein.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- JavaScript for Sidebar Mobile Toggle -->
    <script>
        function toggleSidebar() {
            const sidebar = document.querySelector('.admin-sidebar');
            const backdrop = document.getElementById('sidebarBackdrop');
            if (sidebar) {
                sidebar.classList.toggle('sidebar-open');
                sidebar.classList.toggle('show');
            }
            if (backdrop) {
                backdrop.classList.toggle('show-backdrop');
            }
        }
    </script>
</body>
</html>