<?php
require_once 'auth_check.php';
include 'sidebar.php';
require_once 'db.php';

// Ensure the database connection imported from db.php is available to this file.
$conn =$GLOBALS['conn'] ?? null;

$message = '';$error = '';

// Auto-Ensure Required Database Table & Columns Exist
if ($conn) {
    mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `hotels` (
        `id` INT PRIMARY KEY AUTO_INCREMENT,
        `name` VARCHAR(255) NOT NULL,
        `location` VARCHAR(255) DEFAULT NULL,
        `category` VARCHAR(100) DEFAULT NULL,
        `price` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        `description` TEXT DEFAULT NULL,
        `image` VARCHAR(255) DEFAULT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    // Check & Add Missing 'image' Column if Table Exists
    $check_col = mysqli_query($conn, "SHOW COLUMNS FROM `hotels` LIKE 'image'");
    if ($check_col && mysqli_num_rows($check_col) == 0) {
        mysqli_query($conn, "ALTER TABLE `hotels` ADD `image` VARCHAR(255) DEFAULT NULL AFTER `description`");
    }

    // Check & Add Missing 'price' Column if Table Exists
    $check_price = mysqli_query($conn, "SHOW COLUMNS FROM `hotels` LIKE 'price'");
    if ($check_price && mysqli_num_rows($check_price) == 0) {
        mysqli_query($conn, "ALTER TABLE `hotels` ADD `price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 AFTER `category`");
    }
}

// Hotel Add Karne Ka Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_hotel'])) {$hotel_name  = trim($_POST['hotel_name'] ?? '');$location    = trim($_POST['location'] ?? '');$category    = trim($_POST['category'] ?? '');$price       = trim($_POST['price'] ?? 0);$description = trim($_POST['description'] ?? '');$image_name  = '';

    if (!empty($hotel_name)) {
        // Image Upload Handle
        if (isset($_FILES['hotel_image']) && $_FILES['hotel_image']['error'] === 0) {$target_dir = "../images/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
            $image_name = time() . '_' . basename($_FILES['hotel_image']['name']);$target_file = $target_dir .$image_name;
            move_uploaded_file($_FILES['hotel_image']['tmp_name'],$target_file);
        }

        // Table me insert logic
        $stmt = mysqli_prepare($conn, "INSERT INTO hotels (name, location, category, price, description, image) VALUES (?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "sssdss", $hotel_name, $location, $category, $price, $description, $image_name);
            if (mysqli_stmt_execute($stmt)) {$message = "Hotel successfully add ho gaya!";
            } else {
                $error = "Hotel add karne me error aaya: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            $error = "Database query error: " . mysqli_error($conn);
        }
    } else {
        $error = "Hotel name zaroori hai!";
    }
}

// Hotel Delete Karne Ka Logic
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = mysqli_prepare($conn, "DELETE FROM hotels WHERE id = ?");
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $delete_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
        header("Location: manage-hotels.php?msg=deleted");
        exit();
    }
}

// Hotels Fetch Karein
$query = "SELECT * FROM hotels 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 Hotels & Stay | 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;
        }

        /* SIDEBAR STYLING */
        .admin-sidebar {
            width: var(--sidebar-width);
            background-color: var(--dark-navy);
            color: #ffffff;
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            display: flex;
            flex-direction: column;
            z-index: 100;
            box-shadow: 4px 0 15px rgba(0, 0, 0, 0.05);
        }

        .sidebar-brand {
            padding: 24px 20px;
            background: rgba(0, 0, 0, 0.25);
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }

        .sidebar-brand h2 {
            font-size: 22px;
            color: var(--brand-saffron);
            letter-spacing: 1.5px;
            font-weight: 700;
        }

        .sidebar-brand p {
            font-size: 11px;
            color: #94A3B8;
            margin-top: 2px;
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
            flex: 1;
            overflow-y: auto;
        }

        .sidebar-menu li a {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 13px 24px;
            color: #CBD5E1;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.25s ease;
        }

        .sidebar-menu li a:hover, 
        .sidebar-menu li.active a {
            background: rgba(255, 255, 255, 0.08);
            color: #ffffff;
            border-left: 4px solid var(--brand-saffron);
        }

        .sidebar-menu li a i {
            font-size: 16px;
            width: 20px;
            text-align: center;
        }

        /* MAIN WRAPPER */
        .admin-main {
            margin-left: var(--sidebar-width);
            flex: 1;
            display: flex;
            flex-direction: column;
            width: calc(100% - var(--sidebar-width));
        }

        .admin-topbar {
            background: #ffffff;
            height: 70px;
            padding: 0 35px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .topbar-title {
            font-size: 15px;
            color: var(--dark-navy);
            font-weight: 600;
        }

        .btn-logout {
            padding: 8px 16px;
            background: #FEF2F2;
            color: #EF4444;
            border-radius: 8px;
            text-decoration: none;
            font-size: 13px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
            border: 1px solid #FCA5A5;
        }

        .btn-logout:hover {
            background: #EF4444;
            color: #ffffff;
        }

        .admin-content {
            padding: 35px;
        }

        .page-title {
            font-size: 22px;
            color: var(--dark-navy);
            margin-bottom: 25px;
            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: 8px;
        }

        .form-group input, 
        .form-group select, 
        .form-group textarea {
            width: 100%;
            padding: 12px 14px;
            border: 1.5px solid #CBD5E1;
            border-radius: 10px;
            font-size: 14px;
            outline: none;
            transition: all 0.25s ease;
            background-color: #fff;
        }

        .form-group input:focus, 
        .form-group select:focus, 
        .form-group textarea:focus {
            border-color: var(--brand-green);
            box-shadow: 0 0 0 3px rgba(18, 82, 31, 0.1);
        }

        .btn-add {
            background: var(--brand-green);
            color: #ffffff;
            padding: 12px 22px;
            border: none;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.2s ease;
            box-shadow: 0 4px 12px rgba(18, 82, 31, 0.15);
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-add:hover {
            background: #0d3d17;
        }

        .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: #F1F5F9;
            color: var(--dark-navy);
            font-weight: 600;
            padding: 14px 18px;
            border-bottom: 1px solid #E2E8F0;
        }

        td {
            padding: 14px 18px;
            border-bottom: 1px solid #E2E8F0;
            color: #334155;
            vertical-align: middle;
        }

        tr:hover {
            background-color: #F8FAFC;
        }

        .btn-delete {
            color: #EF4444;
            background: #FEF2F2;
            padding: 6px 12px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn-delete:hover {
            background: #EF4444;
            color: #ffffff;
        }

        .alert-success {
            padding: 12px 16px;
            background: #DCFCE7;
            color: #166534;
            border-radius: 8px;
            font-size: 13px;
            margin-bottom: 20px;
            border: 1px solid #BBF7D0;
        }

        .alert-error {
            padding: 12px 16px;
            background: #FEF2F2;
            color: #991B1B;
            border-radius: 8px;
            font-size: 13px;
            margin-bottom: 20px;
            border: 1px solid #FCA5A5;
        }

        /* RESPONSIVE DESIGN */
        @media (max-width: 768px) {
            .admin-sidebar {
                width: 70px;
            }
            .sidebar-brand h2,
            .sidebar-brand p,
            .sidebar-menu li a span {
                display: none;
            }
            .admin-main {
                margin-left: 70px;
                width: calc(100% - 70px);
            }
            .sidebar-menu li a {
                justify-content: center;
                padding: 16px;
            }
            .admin-content {
                padding: 20px;
            }
            .admin-topbar {
                padding: 0 20px;
            }
        }
    </style>
</head>
<body>

    <!-- MAIN WRAPPER -->
    <div class="admin-main">
        <header class="admin-topbar">
            <div class="topbar-title">
                <i class="fas fa-hotel" style="color: var(--brand-green); margin-right: 6px;"></i> Hotels & Accommodation
            </div>
            <a href="logout.php" class="btn-logout"><i class="fas fa-power-off"></i> Logout</a>
        </header>

        <main class="admin-content">
            <h1 class="page-title">Manage Hotels</h1>

            <?php if (!empty($message) || (isset($_GET['msg']) &&$_GET['msg'] === 'deleted')): ?>
                <div class="alert-success"><?php echo !empty($message) ?$message : 'Hotel successfully delete ho gaya!'; ?></div>
            <?php endif; ?>

            <?php if (!empty($error)): ?>
                <div class="alert-error"><?php echo $error; ?></div>
            <?php endif; ?>

            <!-- ADD HOTEL FORM -->
            <div class="card">
                <h3 style="margin-bottom: 20px; font-size: 16px; color: var(--dark-navy); font-weight: 600;">Add New Hotel / Accommodation</h3>
                <form action="" method="POST" enctype="multipart/form-data">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Hotel Name</label>
                            <input type="text" name="hotel_name" placeholder="e.g. Hotel Grand Kedarnath" required>
                        </div>
                        <div class="form-group">
                            <label>Location</label>
                            <input type="text" name="location" placeholder="e.g. Guptkashi / Phata / Badrinath">
                        </div>
                        <div class="form-group">
                            <label>Category / Star</label>
                            <select name="category">
                                <option value="3 Star">3 Star</option>
                                <option value="4 Star">4 Star</option>
                                <option value="5 Star">5 Star</option>
                                <option value="Luxury Resort">Luxury Resort</option>
                                <option value="Homestay">Homestay / Cottage</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Price (₹ per night)</label>
                            <input type="number" step="0.01" name="price" placeholder="e.g. 2500" required>
                        </div>
                        <div class="form-group">
                            <label>Hotel Image</label>
                            <input type="file" name="hotel_image" accept="image/*">
                        </div>
                    </div>
                    <div class="form-group" style="margin-bottom: 20px;">
                        <label>Description / Facilities</label>
                        <textarea name="description" rows="3" placeholder="Facilities, food service, distance from helipad..."></textarea>
                    </div>
                    <button type="submit" name="add_hotel" class="btn-add"><i class="fas fa-plus"></i> Add Hotel</button>
                </form>
            </div>

            <!-- HOTELS TABLE -->
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>#ID</th>
                            <th>Image</th>
                            <th>Hotel Name</th>
                            <th>Location</th>
                            <th>Category</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>#<?php echo $row['id']; ?></td>
                                    <td>
                                        <?php if (!empty($row['image'])): ?>
                                            <img src="../images/<?php echo htmlspecialchars($row['image']); ?>" width="50" height="40" style="object-fit:cover; border-radius:6px;">
                                        <?php else: ?>
                                            <span style="color:#94A3B8; font-size:11px;">No Image</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><strong><?php echo htmlspecialchars($row['name'] ?? $row['hotel_name'] ?? ''); ?></strong></td>
                                    <td><?php echo htmlspecialchars($row['location'] ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($row['category'] ?? 'N/A'); ?></td>
                                    <td><strong style="color: var(--brand-green);">₹<?php echo number_format((float)($row['price'] ?? 0), 2); ?></strong></td>
                                    <td><?php echo htmlspecialchars($row['description'] ?? ''); ?></td>
                                    <td>
                                        <a href="manage-hotels.php?delete_id=<?php echo $row['id']; ?>" class="btn-delete" onclick="return confirm('Is hotel ko delete karna chahte hain?');">
                                            <i class="fas fa-trash"></i> Delete
                                        </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" style="text-align: center; color: #94A3B8; padding: 25px;">Koi hotel record nahi mila. Pehle add karein.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

</body>
</html>