<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config.php';

// Auth Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

global $pdo;
$message = '';

// ==========================================
// 1. DELETE CATEGORY
// ==========================================
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("SELECT image FROM categories WHERE id = ?");
    $stmt->execute([$id]);
    $img = $stmt->fetchColumn();
    
    // Delete image file if it exists and isn't the default one
    if($img && $img != 'default-category.png' && file_exists("../assets/images/categories/" . $img)) {
        unlink("../assets/images/categories/" . $img);
    }
    
    $pdo->prepare("DELETE FROM categories WHERE id = ?")->execute([$id]);
    $message = "Category Deleted Successfully!";
}

// ==========================================
// 2. ADD NEW CATEGORY
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_category'])) {
    $name = trim($_POST['name']);
    $slug = strtolower(str_replace(' ', '-', $name));
    $icon = trim($_POST['icon']);
    $imageName = 'default-category.png';
    
    if (!empty($_FILES['image']['name'])) {
        $targetDir = "../assets/images/categories/";
        if (!file_exists($targetDir)) mkdir($targetDir, 0777, true);
        
        $imageName = time() . '_' . basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $imageName);
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO categories (name, slug, icon, image, is_active) VALUES (?, ?, ?, ?, 1)");
        $stmt->execute([$name, $slug, $icon, $imageName]);
        $message = "Category Added Successfully!";
    } catch(Exception $e) {
        $message = "Error: Category name already exists!";
    }
}

// ==========================================
// 3. EDIT / UPDATE CATEGORY
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_category'])) {
    $id = $_POST['cat_id'];
    $name = trim($_POST['name']);
    $slug = strtolower(str_replace(' ', '-', $name));
    $icon = trim($_POST['icon']);
    
    // Agar nayi image upload ki hai toh usko update karo
    if (!empty($_FILES['image']['name'])) {
        $targetDir = "../assets/images/categories/";
        if (!file_exists($targetDir)) mkdir($targetDir, 0777, true);
        
        $imageName = time() . '_' . basename($_FILES['image']['name']);
        move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $imageName);
        
        $stmt = $pdo->prepare("UPDATE categories SET name=?, slug=?, icon=?, image=? WHERE id=?");
        $stmt->execute([$name, $slug, $icon, $imageName, $id]);
    } else {
        // Bina image ke sirf naam aur icon update karo
        $stmt = $pdo->prepare("UPDATE categories SET name=?, slug=?, icon=? WHERE id=?");
        $stmt->execute([$name, $slug, $icon, $id]);
    }
    $message = "Category Updated Successfully!";
}

// Fetch all categories for table
$categories = $pdo->query("SELECT * FROM categories ORDER BY display_order ASC")->fetchAll();

$pageTitle = "Manage Categories";
require_once 'includes/header.php';
?>

<style>
    .cat-img { width: 50px; height: 50px; object-fit: cover; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);}
    .icon-preview { width: 50px; height: 50px; border-radius: 10px; background: #f0f2f5; display: flex; align-items: center; justify-content: center; font-size: 24px; color: #e74c3c;}
</style>

<?php if($message): ?>
    <div class="alert alert-success fw-bold border-0 shadow-sm"><i class="fas fa-check-circle"></i> <?= $message ?></div>
<?php endif; ?>

<div class="custom-card mb-4">
    <div class="custom-card-header">
        <h6 class="m-0 fw-bold"><i class="fas fa-plus-circle text-primary"></i> Add New Category</h6>
    </div>
    <div class="card-body p-4">
        <form method="POST" enctype="multipart/form-data" class="row align-items-end g-3">
            <input type="hidden" name="add_category" value="1">
            <div class="col-md-3">
                <label class="form-label fw-bold">Category Name</label>
                <input type="text" name="name" class="form-control" placeholder="e.g. Live Casino" required>
            </div>
            <div class="col-md-3">
                <label class="form-label fw-bold">Icon (FontAwesome)</label>
                <input type="text" name="icon" class="form-control" placeholder="e.g. dice, gamepad, coins">
            </div>
            <div class="col-md-4">
                <label class="form-label fw-bold">Category Image (Optional)</label>
                <input type="file" name="image" class="form-control" accept="image/png, image/jpeg, image/jpg">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100 fw-bold"><i class="fas fa-plus"></i> Add</button>
            </div>
        </form>
    </div>
</div>

<div class="custom-card">
    <div class="custom-card-header">
        <h6 class="m-0 fw-bold"><i class="fas fa-list text-primary"></i> Current Categories</h6>
    </div>
    <div class="table-responsive">
        <table class="table table-hover align-middle m-0">
            <thead class="table-light">
                <tr>
                    <th class="ps-4">ID</th>
                    <th>Image / Icon</th>
                    <th>Category Name</th>
                    <th>Status</th>
                    <th class="pe-4 text-end">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($categories)): foreach($categories as $c): ?>
                <tr>
                    <td class="ps-4 fw-bold text-muted">#<?= $c['id'] ?></td>
                    <td>
                        <?php if(!empty($c['image']) && $c['image'] != 'default-category.png'): ?>
                            <img src="../assets/images/categories/<?= htmlspecialchars($c['image']) ?>" class="cat-img">
                        <?php else: ?>
                            <div class="icon-preview"><i class="fas fa-<?= htmlspecialchars($c['icon'] ?? 'gamepad') ?>"></i></div>
                        <?php endif; ?>
                    </td>
                    <td class="fw-bold text-dark fs-6"><?= htmlspecialchars($c['name']) ?></td>
                    <td><span class="badge bg-success px-3 py-2 rounded-pill">Active</span></td>
                    <td class="pe-4 text-end">
                        <button class="btn btn-sm btn-info text-white fw-bold me-2" onclick="openEditModal(<?= $c['id'] ?>, '<?= addslashes($c['name']) ?>', '<?= addslashes($c['icon']) ?>')">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <a href="categories.php?delete=<?= $c['id'] ?>" class="btn btn-sm btn-danger fw-bold" onclick="return confirm('Delete this category? Games inside it might not show up properly!');">
                            <i class="fas fa-trash"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; else: ?>
                <tr><td colspan="5" class="text-center text-muted py-5"><i class="fas fa-folder-open mb-2 fs-1"></i><br>No categories found. Add your first category!</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold"><i class="fas fa-edit text-primary"></i> Edit Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body p-4">
                    <input type="hidden" name="edit_category" value="1">
                    <input type="hidden" name="cat_id" id="edit_cat_id">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">Category Name</label>
                        <input type="text" name="name" id="edit_name" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">Icon (FontAwesome)</label>
                        <input type="text" name="icon" id="edit_icon" class="form-control">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">Upload New Image (Optional)</label>
                        <input type="file" name="image" class="form-control" accept="image/png, image/jpeg, image/jpg">
                        <small class="text-muted">Leave empty if you don't want to change the image.</small>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary fw-bold" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success fw-bold"><i class="fas fa-save"></i> Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Function to pass data from PHP Table to the Edit Modal
function openEditModal(id, name, icon) {
    document.getElementById('edit_cat_id').value = id;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_icon').value = icon;
    
    // Show the modal
    var myModal = new bootstrap.Modal(document.getElementById('editModal'));
    myModal.show();
}
</script>

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