<?php
/**
 * Manage Categories (Ultra-Premium Admin UI - Mobile Responsive + Editable)
 */
require_once 'header.php';

// Force UTF-8 and Emoji Support
try {
    $pdo->exec("SET NAMES utf8mb4");
} catch(Exception $e) {}

$success = '';
$error = '';

// ১. ক্যাটাগরি আপলোড ফোল্ডার নিশ্চিত করা
$cat_dir = '../uploads/categories/';
if (!is_dir($cat_dir)) {
    mkdir($cat_dir, 0777, true);
}

// (Safety) যদি ডাটাবেসে categories টেবিল না থাকে, তবে অটোমেটিক তৈরি করে নিবে
try {
    $pdo->query("SELECT 1 FROM categories LIMIT 1");
} catch (PDOException $e) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS categories (
        id INT AUTO_INCREMENT PRIMARY KEY, 
        name VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, 
        icon VARCHAR(255) NOT NULL, 
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

// ২. ক্যাটাগরি যোগ করার লজিক
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_category'])) {
    $name = trim($_POST['name']);
    
    if (empty($name)) {
        $error = "Category name is required.";
    } elseif (isset($_FILES['icon']) && $_FILES['icon']['error'] === 0) {
        $ext = strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION));
        $allowed = ['png', 'jpg', 'jpeg', 'svg', 'webp'];

        if (in_array($ext, $allowed)) {
            $icon_name = 'cat_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['icon']['tmp_name'], $cat_dir . $icon_name)) {
                $stmt = $pdo->prepare("INSERT INTO categories (name, icon) VALUES (?, ?)");
                $stmt->execute([$name, $icon_name]);
                $success = "Category added successfully!";
            } else {
                $error = "Failed to upload icon.";
            }
        } else {
            $error = "Invalid icon format. Use PNG, JPG, WEBP, or SVG.";
        }
    } else {
        $error = "Please upload a category icon.";
    }
}

// ক্যাটাগরি আপডেট করার লজিক
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_category'])) {
    $id = (int)$_POST['cat_id'];
    $name = trim($_POST['name']);
    
    if (empty($name)) {
        $error = "Category name is required.";
    } else {
        // Fetch current icon
        $stmt = $pdo->prepare("SELECT icon FROM categories WHERE id = ?");
        $stmt->execute([$id]);
        $current_cat = $stmt->fetch();
        $icon_name = $current_cat['icon'];

        if (isset($_FILES['icon']) && $_FILES['icon']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION));
            $allowed = ['png', 'jpg', 'jpeg', 'svg', 'webp'];

            if (in_array($ext, $allowed)) {
                $new_icon_name = 'cat_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['icon']['tmp_name'], $cat_dir . $new_icon_name)) {
                    if (file_exists($cat_dir . $icon_name)) {
                        @unlink($cat_dir . $icon_name);
                    }
                    $icon_name = $new_icon_name;
                } else {
                    $error = "Failed to upload new icon.";
                }
            } else {
                $error = "Invalid icon format. Use PNG, JPG, WEBP, or SVG.";
            }
        }

        if (empty($error)) {
            $stmt = $pdo->prepare("UPDATE categories SET name = ?, icon = ? WHERE id = ?");
            $stmt->execute([$name, $icon_name, $id]);
            $success = "Category updated successfully!";
        }
    }
}

// ৩. ক্যাটাগরি ডিলিট করার লজিক
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    // ডিলিট করার আগে আইকন ফাইলটি মুছে ফেলা
    $stmt = $pdo->prepare("SELECT icon FROM categories WHERE id = ?");
    $stmt->execute([$id]);
    $cat = $stmt->fetch();
    if ($cat && file_exists($cat_dir . $cat['icon'])) {
        unlink($cat_dir . $cat['icon']);
    }

    $pdo->prepare("DELETE FROM categories WHERE id = ?")->execute([$id]);
    $success = "Category deleted successfully!";
}

// ক্যাটাগরি লিস্ট ফেচ করা
$categories = $pdo->query("SELECT * FROM categories ORDER BY id DESC")->fetchAll();

// Edit State
$edit_mode = false;
$edit_data = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_data = $stmt->fetch();
    if ($edit_data) {
        $edit_mode = true;
    }
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    :root {
        --primary: #84cc16; /* Light Green */
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #1e293b;
        --text-muted: #64748b;
    }

    *, *::before, *::after {
        box-sizing: border-box;
    }

    body { 
        background: var(--bg-light); 
        color: var(--text-main); 
        font-family: 'Inter', sans-serif; 
        margin: 0; 
        padding: 0; 
        overflow-x: hidden; 
    }
    
    .settings-container { 
        width: 100%; 
        max-width: 1100px; 
        margin: 0 auto; 
        padding: 20px 15px; 
    }
    
    .page-title { 
        font-size: 1.5rem; 
        font-weight: 800; 
        margin: 0 0 20px 0; 
        color: var(--text-main); 
    }

    .grid-layout {
        display: grid; 
        grid-template-columns: 320px minmax(0, 1fr);
        gap: 20px; 
        align-items: start;
        width: 100%;
    }

    .admin-card { 
        background: var(--card-bg); 
        border-radius: 12px; 
        padding: 20px; 
        border: 1px solid var(--border); 
        margin-bottom: 20px; 
        box-shadow: none;
        width: 100%;
        overflow: hidden;
    }

    .card-title { 
        margin: 0 0 15px 0; 
        font-size: 1.1rem; 
        font-weight: 700; 
        color: var(--text-main); 
        border-bottom: 1px solid var(--border); 
        padding-bottom: 12px; 
    }

    .form-group { margin-bottom: 15px; width: 100%; }
    .form-label { display: block; font-size: 0.85rem; font-weight: 600; margin-bottom: 6px; color: var(--text-main); }
    .form-control { 
        width: 100%; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; 
        font-size: 0.9rem; transition: 0.2s; background: transparent;
    }
    .form-control:focus { border-color: var(--primary); outline: none; }
    
    .file-upload-box { 
        width: 100%; border: 2px dashed var(--border); padding: 20px; border-radius: 10px; 
        text-align: center; background: #fafafa; cursor: pointer; position: relative; transition: 0.3s; 
    }
    .file-upload-box:hover { border-color: var(--primary); background: #f4fce3; }
    .file-upload-box input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
    
    .btn-submit { 
        background: var(--primary); color: white; padding: 12px; border: none; 
        border-radius: 8px; font-weight: 700; font-size: 0.95rem; cursor: pointer; width: 100%; transition: 0.3s; 
    }
    .btn-submit:hover { background: var(--primary-hover); }
    
    .btn-cancel {
        background: #f1f5f9; color: #475569; padding: 12px; border: none; 
        border-radius: 8px; font-weight: 600; font-size: 0.95rem; cursor: pointer; width: 100%; 
        transition: 0.3s; margin-top: 10px; display: block; text-align: center; text-decoration: none; 
    }
    .btn-cancel:hover { background: #e2e8f0; color: #1e293b; }

    /* Table Design */
    .table-responsive { 
        width: 100%; 
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch; 
        display: block;
    }
    
    .data-table { 
        width: 100%; 
        border-collapse: collapse; 
        text-align: left; 
        min-width: 450px; 
    }
    
    .data-table th { padding: 12px 15px; font-size: 0.8rem; color: var(--text-muted); font-weight: 600; border-bottom: 1px solid var(--border); text-transform: uppercase; background: #fafafa; white-space: nowrap; }
    .data-table td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 0.9rem; color: var(--text-main); vertical-align: middle; font-weight: 500; }
    .data-table tr:last-child td { border-bottom: none; }
    
    .cat-icon { width: 45px; height: 45px; border-radius: 8px; object-fit: contain; background: #f1f5f9; padding: 6px; border: 1px solid var(--border); display: block; }
    
    .action-btns { display: flex; gap: 8px; justify-content: flex-end; }
    .btn-edit { color: #3b82f6; background: #eff6ff; padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 0.8rem; font-weight: 600; transition: 0.2s; border: 1px solid transparent; white-space: nowrap; }
    .btn-edit:hover { background: #dbeafe; border-color: #bfdbfe; }
    .btn-delete { color: #ef4444; background: #fef2f2; padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 0.8rem; font-weight: 600; transition: 0.2s; border: 1px solid transparent; white-space: nowrap; }
    .btn-delete:hover { background: #fee2e2; border-color: #fecaca; }

    /* Toast */
    .toast-success { background: #10b981 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #059669 !important; padding: 10px 20px !important; }
    .toast-error { background: #ef4444 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #b91c1c !important; padding: 10px 20px !important; }

    @media (max-width: 850px) {
        .grid-layout { grid-template-columns: 1fr; }
        .admin-card { padding: 15px; }
    }
</style>

<div class="settings-container">
    <h1 class="page-title">Manage Categories</h1>

    <div class="grid-layout">
        
        <div>
            <?php if(!$edit_mode): ?>
            <div class="admin-card">
                <h3 class="card-title">Add New Category</h3>
                <form action="" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
                    <input type="hidden" name="add_category" value="1">
                    
                    <div class="form-group">
                        <label class="form-label">Category Name *</label>
                        <input type="text" name="name" class="form-control" placeholder="e.g. PHP Scripts" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Category Icon *</label>
                        <div class="file-upload-box">
                            <div style="font-weight: 600; font-size: 0.85rem; color: var(--text-main);">Upload PNG/SVG/WEBP</div>
                            <input type="file" name="icon" accept=".png,.jpg,.jpeg,.svg,.webp" required>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-submit">Create Category</button>
                </form>
            </div>
            <?php else: ?>
            <div class="admin-card" style="border-color: #bfdbfe; background: #f8fafc;">
                <h3 class="card-title" style="color: #1e3a8a;">Edit Category</h3>
                <form action="categories.php" method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
                    <input type="hidden" name="update_category" value="1">
                    <input type="hidden" name="cat_id" value="<?php echo $edit_data['id']; ?>">
                    
                    <div style="margin-bottom: 15px; text-align: center;">
                        <img src="../uploads/categories/<?php echo htmlspecialchars($edit_data['icon'], ENT_QUOTES, 'UTF-8'); ?>" style="width: 80px; height: 80px; object-fit: contain; border-radius: 8px; border: 1px solid var(--border); background: #fff; padding: 10px;">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Category Name *</label>
                        <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($edit_data['name'], ENT_QUOTES, 'UTF-8'); ?>" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Change Icon (Optional)</label>
                        <div class="file-upload-box" style="padding: 15px;">
                            <div style="font-weight: 600; font-size: 0.8rem;">Upload New Icon</div>
                            <input type="file" name="icon" accept=".png,.jpg,.jpeg,.svg,.webp">
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-submit">Update Category</button>
                    <a href="categories.php" class="btn-cancel">Cancel Edit</a>
                </form>
            </div>
            <?php endif; ?>
        </div>

        <div class="admin-card">
            <h3 class="card-title">Existing Categories</h3>
            
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th style="width: 60px;">Icon</th>
                            <th>Category Name</th>
                            <th style="text-align: right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($categories as $cat): ?>
                        <tr style="<?php echo $cat['id'] == ($edit_data['id'] ?? 0) ? 'background: #f0fdf4;' : ''; ?>">
                            <td>
                                <img src="../uploads/categories/<?php echo htmlspecialchars($cat['icon'], ENT_QUOTES, 'UTF-8'); ?>" alt="Icon" class="cat-icon" onerror="this.src='https://via.placeholder.com/45';">
                            </td>
                            <td><?php echo htmlspecialchars($cat['name'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td>
                                <div class="action-btns">
                                    <a href="?edit=<?php echo $cat['id']; ?>" class="btn-edit">Edit</a>
                                    <a href="?delete=<?php echo $cat['id']; ?>" onclick="return confirm('Delete this category? Products linked to it might lose their category reference.')" class="btn-delete">Del</a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(count($categories) == 0): ?>
                            <tr><td colspan="3" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 500;">No categories found. Create your first category.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 4000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>
</script>

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