<?php
require 'auth_check.php';
require '../config/db.php';

$msg = "";
$msgClass = "";

// 1. ADD / UPDATE CATEGORY
if (isset($_POST['save_category'])) {
    $name = trim($_POST['name']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    
    // Handle Image Upload
    $img_path = $_POST['current_image'] ?? NULL;
    if (!empty($_FILES['image']['name'])) {
        $target = "../assets/images/cats/" . time() . "_" . $_FILES['image']['name'];
        if (!is_dir("../assets/images/cats/")) mkdir("../assets/images/cats/", 0777, true);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
            $img_path = str_replace("../", "", $target);
        }
    }

    if (!empty($_POST['cat_id'])) {
        // UPDATE
        $stmt = $pdo->prepare("UPDATE categories SET name=?, slug=?, image=? WHERE id=?");
        $stmt->execute([$name, $slug, $img_path, $_POST['cat_id']]);
        $msg = "Category updated!"; $msgClass = "success";
    } else {
        // INSERT
        $stmt = $pdo->prepare("INSERT INTO categories (name, slug, image) VALUES (?, ?, ?)");
        $stmt->execute([$name, $slug, $img_path]);
        $msg = "Category added!"; $msgClass = "success";
    }
}

// 2. DELETE CATEGORY
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM categories WHERE id=?")->execute([$_GET['delete']]);
    header("Location: categories.php?msg=deleted"); exit();
}

// 3. FETCH DATA
$edit_cat = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $edit_cat = $stmt->fetch();
}
$categories = $pdo->query("SELECT * FROM categories ORDER BY id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Categories</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .msg-box { padding: 10px; border-radius: 5px; margin-bottom: 20px; text-align: center; }
        .success { background: #d4edda; color: #155724; }
        
        .form-card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-bottom: 30px; }
        .cat-img { width: 40px; height: 40px; object-fit: contain; border-radius: 4px; background: #eee; }
    </style>
</head>
<body>

<?php include 'sidebar.php'; ?>

    <div class="content">
        <h1>Categories</h1>
        <?php if($msg): ?><div class="msg-box <?php echo $msgClass; ?>"><?php echo $msg; ?></div><?php endif; ?>

        <div class="form-card">
            <h3><?php echo $edit_cat ? "Edit Category" : "Add New Category"; ?></h3>
            <form method="POST" enctype="multipart/form-data" style="display: flex; gap: 10px; align-items: flex-end;">
                <input type="hidden" name="cat_id" value="<?php echo $edit_cat['id'] ?? ''; ?>">
                <input type="hidden" name="current_image" value="<?php echo $edit_cat['image'] ?? ''; ?>">
                
                <div style="flex: 2;">
                    <label style="font-weight:bold; font-size:12px;">Name</label>
                    <input type="text" name="name" class="form-control" required value="<?php echo htmlspecialchars($edit_cat['name'] ?? ''); ?>" style="width:100%; padding:10px; border:1px solid #ddd;">
                </div>
                
                <div style="flex: 1;">
                    <label style="font-weight:bold; font-size:12px;">Icon (Optional)</label>
                    <input type="file" name="image" class="form-control" style="width:100%; padding:7px; border:1px solid #ddd;">
                </div>

                <button type="submit" name="save_category" class="btn btn-primary" style="background:#2c3e50; color:white; border:none; padding:10px 20px; cursor:pointer;">
                    <?php echo $edit_cat ? "Update" : "Create"; ?>
                </button>
                
                <?php if($edit_cat): ?>
                    <a href="categories.php" style="padding:10px; color:red;">Cancel</a>
                <?php endif; ?>
            </form>
        </div>

        <table style="background:white; width:100%; border-collapse:collapse;">
            <thead>
                <tr style="background:#f1f1f1;">
                    <th style="padding:10px;">ID</th>
                    <th>Icon</th>
                    <th>Name</th>
                    <th>Slug</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($categories as $c): ?>
                <tr style="border-bottom:1px solid #eee;">
                    <td style="padding:10px;">#<?php echo $c['id']; ?></td>
                    <td>
                        <?php if($c['image']): ?>
                            <img src="../<?php echo $c['image']; ?>" class="cat-img">
                        <?php else: ?>
                            <span style="color:#ccc;">No Icon</span>
                        <?php endif; ?>
                    </td>
                    <td><strong><?php echo htmlspecialchars($c['name']); ?></strong></td>
                    <td><?php echo $c['slug']; ?></td>
                    <td>
                        <a href="categories.php?edit=<?php echo $c['id']; ?>" style="color:blue; text-decoration:none; margin-right:10px;">Edit</a>
                        <a href="categories.php?delete=<?php echo $c['id']; ?>" style="color:red; text-decoration:none;" onclick="return confirm('Delete this category?')">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</body>
</html>