<?php
require_once '../config/database.php';

if(!isset($_SESSION['is_admin_logged_in']) || $_SESSION['is_admin_logged_in'] !== true) {
    header("Location: index.php");
    exit();
}

$success_msg = '';
$error_msg = '';
$table_missing = false;

// ১. অটোমেটিক টেবিল তৈরি করার অপশন
if(isset($_GET['create_table'])) {
    try {
        $db->exec("CREATE TABLE IF NOT EXISTS `hosting_categories` (
            `id` INT AUTO_INCREMENT PRIMARY KEY,
            `name` VARCHAR(100) NOT NULL,
            `icon` VARCHAR(50) NOT NULL,
            `status` ENUM('active', 'inactive') DEFAULT 'active',
            `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        $success_msg = "Categories table created successfully!";
        header("Location: categories.php"); // রিলোড দিয়ে URL ক্লিন করার জন্য
        exit();
    } catch(PDOException $e) {
        $error_msg = "Table creation failed: " . $e->getMessage();
    }
}

// ২. নতুন ক্যাটাগরি যুক্ত করার কোড
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_category'])) {
    $name = $_POST['name'];
    $icon = $_POST['icon'];
    $status = $_POST['status'];

    try {
        $stmt = $db->prepare("INSERT INTO hosting_categories (name, icon, status) VALUES (:name, :icon, :status)");
        $stmt->execute(['name' => $name, 'icon' => $icon, 'status' => $status]);
        $success_msg = "Category added successfully!";
    } catch(PDOException $e) {
        $error_msg = "Failed to add category. Please make sure the table exists.";
    }
}

// ৩. ডাটাবেস থেকে ক্যাটাগরিগুলো আনা
$categories = [];
try {
    $stmt = $db->query("SELECT * FROM hosting_categories ORDER BY id DESC");
    $categories = $stmt->fetchAll();
} catch(PDOException $e) {
    // যদি টেবিল না থাকে
    $table_missing = true;
}

require_once '../includes/admin_header.php';
require_once '../includes/admin_sidebar.php';
?>

<style>
    /* Premium Glass Card */
    .glass-card {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.5);
        border-radius: 12px;
        box-shadow: 0 8px 30px rgba(0,0,0,0.04);
    }
    
    /* Custom Icon Picker Styling */
    .icon-picker {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 10px;
        max-height: 200px;
        overflow-y: auto;
        padding: 10px;
        background: #f8f9fa;
        border-radius: 8px;
        border: 1px solid #dee2e6;
    }
    .icon-option {
        text-align: center;
        padding: 12px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s;
        border: 2px solid transparent;
        color: #555;
    }
    .icon-option:hover {
        background: rgba(1, 71, 201, 0.1);
        color: var(--primary-blue);
    }
    .icon-option.selected {
        border-color: var(--primary-blue);
        background: rgba(1, 71, 201, 0.15);
        color: var(--primary-blue);
    }
    .icon-option i { font-size: 24px; }
    
    /* Category Card */
    .category-card {
        transition: all 0.3s;
        border: 1px solid #f0f0f0;
    }
    .category-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(1, 71, 201, 0.1) !important;
        border-color: rgba(1, 71, 201, 0.3);
    }
    .cat-icon-wrapper {
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        background: rgba(1, 71, 201, 0.1);
        color: var(--primary-blue);
        font-size: 28px;
    }
</style>

<div id="content">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold" style="color: #2c3e50;"><i class="fas fa-layer-group me-2 text-primary"></i>Hosting Categories</h3>
        
        <!-- Button trigger modal -->
        <button type="button" class="btn btn-primary px-4 fw-semibold" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
            <i class="fas fa-plus-circle me-2"></i>Add New Category
        </button>
    </div>

    <?php if($success_msg): ?>
        <div class="alert alert-success shadow-sm"><i class="fas fa-check-circle me-2"></i> <?= $success_msg ?></div>
    <?php endif; ?>
    <?php if($error_msg): ?>
        <div class="alert alert-danger shadow-sm"><i class="fas fa-exclamation-circle me-2"></i> <?= $error_msg ?></div>
    <?php endif; ?>

    <?php if($table_missing): ?>
        <div class="glass-card p-5 text-center mb-4">
            <h4 class="text-danger mb-3"><i class="fas fa-database fa-2x mb-3"></i><br>Database Table Missing!</h4>
            <p class="text-muted">You need to create the `hosting_categories` table to manage categories.</p>
            <a href="?create_table=true" class="btn btn-success px-4 mt-2"><i class="fas fa-tools me-2"></i>Click Here to Auto-Create Table</a>
        </div>
    <?php else: ?>

        <!-- Categories Grid -->
        <div class="row">
            <?php if(empty($categories)): ?>
                <div class="col-12 text-center py-5">
                    <img src="https://cdn-icons-png.flaticon.com/512/7486/7486747.png" width="100" style="opacity: 0.5;" class="mb-3">
                    <h5 class="text-muted">No categories found.</h5>
                    <p class="text-muted small">Click the "Add New Category" button to create one.</p>
                </div>
            <?php else: ?>
                <?php foreach($categories as $cat): ?>
                    <div class="col-md-4 col-sm-6 mb-4">
                        <div class="card category-card glass-card h-100">
                            <div class="card-body p-4 text-center">
                                <div class="cat-icon-wrapper mx-auto mb-3">
                                    <i class="<?= htmlspecialchars($cat['icon']) ?>"></i>
                                </div>
                                <h5 class="fw-bold mb-2"><?= htmlspecialchars($cat['name']) ?></h5>
                                <span class="badge bg-<?= $cat['status'] == 'active' ? 'success' : 'danger' ?> mb-3 px-3 py-1 rounded-pill">
                                    <?= ucfirst($cat['status']) ?>
                                </span>
                                <div class="d-flex justify-content-center gap-2 mt-2">
                                    <button class="btn btn-sm btn-outline-primary"><i class="fas fa-edit"></i> Edit</button>
                                    <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>

</div> <!-- End of #content -->

<!-- Modal starts OUTSIDE of #content -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 15px;">
            <div class="modal-header bg-light border-bottom-0">
                <h5 class="modal-title fw-bold" id="addCategoryModalLabel" style="color: var(--primary-blue);">
                    <i class="fas fa-plus-circle me-2"></i>Add Category
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <form action="" method="POST" id="categoryForm">
                    <div class="mb-3">
                        <label class="form-label fw-semibold text-muted">Category Name</label>
                        <input type="text" name="name" class="form-control" placeholder="e.g. Shared Hosting, VPS, Dedicated" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold text-muted">Select Icon</label>
                        <input type="hidden" name="icon" id="selectedIcon" value="fas fa-server" required>
                        
                        <div class="icon-picker">
                            <div class="icon-option selected" data-icon="fas fa-server"><i class="fas fa-server"></i></div>
                            <div class="icon-option" data-icon="fas fa-cloud"><i class="fas fa-cloud"></i></div>
                            <div class="icon-option" data-icon="fas fa-globe"><i class="fas fa-globe"></i></div>
                            <div class="icon-option" data-icon="fas fa-database"><i class="fas fa-database"></i></div>
                            <div class="icon-option" data-icon="fas fa-shield-alt"><i class="fas fa-shield-alt"></i></div>
                            <div class="icon-option" data-icon="fab fa-wordpress"><i class="fab fa-wordpress"></i></div>
                            <div class="icon-option" data-icon="fab fa-cpanel"><i class="fab fa-cpanel"></i></div>
                            <div class="icon-option" data-icon="fas fa-microchip"><i class="fas fa-microchip"></i></div>
                            <div class="icon-option" data-icon="fas fa-network-wired"><i class="fas fa-network-wired"></i></div>
                            <div class="icon-option" data-icon="fas fa-hdd"><i class="fas fa-hdd"></i></div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-semibold text-muted">Status</label>
                        <select name="status" class="form-select">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>

                    <button type="submit" name="add_category" class="btn btn-primary w-100 py-2 fw-bold">Save Category</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Icon Picker Logic
    const iconOptions = document.querySelectorAll('.icon-option');
    const selectedIconInput = document.getElementById('selectedIcon');

    iconOptions.forEach(option => {
        option.addEventListener('click', function() {
            // Remove selected class from all
            iconOptions.forEach(opt => opt.classList.remove('selected'));
            
            // Add selected class to clicked icon
            this.classList.add('selected');
            
            // Update hidden input value
            selectedIconInput.value = this.getAttribute('data-icon');
        });
    });
});
</script>

<?php require_once '../includes/admin_footer.php'; ?>