<?php
/**
 * Agentic Square - Premium Admin Dashboard Management Control Panel
 * Categories Management Module (Add & Update Modals with Real-time Auto-slug)
 * CodeCanyon Secure Execution Core Template Architecture
 */

// Inject Core Global Application Engine Paths
require_once __DIR__ . '/../config/config.php';

// Safe verification backup loop check to capture missing connections
if (!isset($conn) || !$conn) {
    die("Critical System Error: Database link reference '$conn' is completely inaccessible or failed to properly initialize.");
}

/** @var mysqli $conn */ 

/**
 * STRICT SECURITY AUDIT GUARD (Envato Marketplace Compliant)
 * Intercepts unauthorized sessions, non-admins, and direct URL entry bypass attempts.
 */
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    // Session is fraudulent or lacks elevation privileges -> Boot safely to root login
    header('Location: ../login.php');
    exit;
}

$status_message = "";
$status_type = "";

// PROCESSING DYNAMIC SQL DATABASE OPERATIONS VIA INBOUND FORMS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ACTION 1: CREATE NEW CATEGORY DISPATCHER
    if (isset($_POST['action']) && $_POST['action'] === 'create_category') {
        $category_name = isset($_POST['category_name']) ? trim(mysqli_real_escape_string($conn, $_POST['category_name'])) : '';
        $slug = isset($_POST['slug']) ? trim(mysqli_real_escape_string($conn, $_POST['slug'])) : '';
        $category_details = isset($_POST['category_details']) ? trim(mysqli_real_escape_string($conn, $_POST['category_details'])) : '';

        if (!empty($category_name) && !empty($slug)) {
            $insert_sql = "INSERT INTO categories (category_name, slug, category_details) VALUES ('$category_name', '$slug', '$category_details')";
            if (mysqli_query($conn, $insert_sql)) {
                $status_message = "Success! New taxonomy category cataloged cleanly.";
                $status_type = "success";
            } else {
                $status_message = "Error! Duplicate reference tracking detected: Slug already exists.";
                $status_type = "error";
            }
        } else {
            $status_message = "Error! All fields are mandatory to build database rows.";
            $status_type = "error";
        }
    }

    // ACTION 2: UPDATE ALTERATION DATA RECORD MODIFICATION
    if (isset($_POST['action']) && $_POST['action'] === 'update_category') {
        $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
        $category_name = isset($_POST['category_name']) ? trim(mysqli_real_escape_string($conn, $_POST['category_name'])) : '';
        $slug = isset($_POST['slug']) ? trim(mysqli_real_escape_string($conn, $_POST['slug'])) : '';
        $category_details = isset($_POST['category_details']) ? trim(mysqli_real_escape_string($conn, $_POST['category_details'])) : '';

        if ($category_id > 0 && !empty($category_name) && !empty($slug)) {
            $update_sql = "UPDATE categories SET category_name = '$category_name', slug = '$slug', category_details = '$category_details' WHERE id = $category_id";
            if (mysqli_query($conn, $update_sql)) {
                $status_message = "Success! Category table logs refreshed successfully.";
                $status_type = "success";
            } else {
                $status_message = "Error! Unable to rewrite entry rows. Check constraints.";
                $status_type = "error";
            }
        } else {
            $status_message = "Error! Failed execution target: Missing valid identifiers.";
            $status_type = "error";
        }
    }
}

// HYDRATE AND RETRIEVE SYSTEM CATEGORY DATASET RECORDS
$categories_result = mysqli_query($conn, "SELECT * FROM categories ORDER BY id DESC");

// CodeCanyon Production Standard Guideline: Inject standard secure UI Header Wrapper layout component
require_once __DIR__ . '/../sections/header.php';
?>

<div class="min-h-screen bg-nftDark text-white antialiased">
    
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-12 px-4 sm:px-6 lg:px-8 transition-all duration-300">
        <div class="max-w-7xl mx-auto space-y-8">
            
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-900 pb-6">
                <div>
                    <h1 class="text-3xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-white to-nftAccentCyan">Taxonomy Categories</h1>
                    <p class="text-sm text-nftTextGray mt-1">Hello, <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Admin', ENT_QUOTES, 'UTF-8'); ?>! Build, review, alter, and manage directory categories for market items.</p>
                </div>
                <div>
                    <button onclick="openModal('addCategoryModal')" class="btn-gradient px-5 py-3 rounded-xl text-xs font-bold tracking-widest uppercase shadow-lg shadow-cyan-500/10 transition-all hover:scale-[1.02] active:scale-[0.98] text-white flex items-center">
                        <i class="fa-solid fa-folder-plus mr-2 text-sm"></i> Add Category
                    </button>
                </div>
            </div>

            <?php if (!empty($status_message)): ?>
                <div class="p-4 rounded-xl text-xs font-bold tracking-wide flex items-center space-x-3 <?php echo ($status_type === 'success') ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400' : 'bg-rose-500/10 border border-rose-500/20 text-rose-400'; ?>">
                    <i class="fa-solid <?php echo ($status_type === 'success') ? 'fa-circle-check' : 'fa-triangle-exclamation'; ?> text-base"></i>
                    <span>SYSTEM NOTIFICATION: <?php echo htmlspecialchars($status_message, ENT_QUOTES, 'UTF-8'); ?></span>
                </div>
            <?php endif; ?>

            <div class="glass-card rounded-2xl border border-slate-800/80 overflow-hidden">
                <div class="p-6 border-b border-slate-900 flex items-center justify-between">
                    <div>
                        <h3 class="font-bold text-base">Active Base Categories</h3>
                        <p class="text-xs text-nftTextGray mt-0.5">Live store filtering routing entries mapping to store storefront pipelines.</p>
                    </div>
                    <span class="w-2.5 h-2.5 bg-nftAccentCyan rounded-full shadow-lg shadow-cyan-400/50"></span>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-900 bg-slate-950/20 text-xs font-bold text-nftTextGray uppercase tracking-wider">
                                <th class="py-4 px-6 w-24">ID Reference</th>
                                <th class="py-4 px-6 w-1/4">Category Display Title</th>
                                <th class="py-4 px-6 w-1/4">System Routing Slug</th>
                                <th class="py-4 px-6">Description / Details Matrix</th>
                                <th class="py-4 px-6 text-center w-40">Actions Matrix</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-900/40 text-xs text-slate-300 font-medium">
                            <?php if ($categories_result && mysqli_num_rows($categories_result) > 0): ?>
                                <?php while ($row = mysqli_fetch_assoc($categories_result)): ?>
                                    <tr class="hover:bg-slate-900/10 transition-colors group">
                                        <td class="py-4 px-6 font-mono text-nftTextGray">#<?php echo $row['id']; ?></td>
                                        <td class="py-4 px-6 font-bold text-white group-hover:text-nftAccentCyan transition-colors">
                                            <?php echo htmlspecialchars($row['category_name'], ENT_QUOTES, 'UTF-8'); ?>
                                        </td>
                                        <td class="py-4 px-6">
                                            <span class="font-mono text-xs text-nftAccentPurple bg-nftAccentPurple/5 border border-nftAccentPurple/10 px-2.5 py-1 rounded-md">
                                                <?php echo htmlspecialchars($row['slug'], ENT_QUOTES, 'UTF-8'); ?>
                                            </span>
                                        </td>
                                        <td class="py-4 px-6 text-nftTextGray max-w-xs truncate">
                                            <?php echo !empty($row['category_details']) ? htmlspecialchars($row['category_details'], ENT_QUOTES, 'UTF-8') : '<span class="italic text-slate-700">No descriptive text provided.</span>'; ?>
                                        </td>
                                        <td class="py-4 px-6 text-center">
                                            <button 
                                                onclick="triggerUpdateContext(<?php echo $row['id']; ?>, '<?php echo htmlspecialchars(addslashes($row['category_name']), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(addslashes($row['slug']), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(addslashes($row['category_details'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>')"
                                                class="text-xs bg-slate-950 border border-slate-800/80 hover:border-nftAccentCyan/30 text-nftTextGray hover:text-nftAccentCyan font-bold px-4 py-2 rounded-xl transition-all duration-200"
                                            >
                                                <i class="fa-solid fa-pen-to-square mr-1.5"></i>Update
                                            </button>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="py-12 text-center text-nftTextGray">
                                        <i class="fa-solid fa-tags text-4xl mb-3 block text-slate-800"></i>
                                        No taxonomy metrics registered. Click add button to commit a category.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </main>

</div>

<div id="addCategoryModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm hidden p-4 transition-all duration-300">
    <div class="w-full max-w-md bg-nftDark border border-slate-800/80 rounded-2xl shadow-2xl shadow-black/80 overflow-hidden relative transform transition-all">
        <div class="p-6 border-b border-slate-900 flex items-center justify-between bg-slate-950/40">
            <h3 class="text-lg font-bold tracking-wide text-white flex items-center">
                <i class="fa-solid fa-folder-plus mr-2.5 text-nftAccentCyan"></i> Create Store Category
            </h3>
            <button onclick="closeModal('addCategoryModal')" class="w-8 h-8 rounded-lg bg-slate-950 flex items-center justify-center border border-slate-800 text-nftTextGray hover:text-white transition-colors">
                <i class="fa-solid fa-xmark text-sm"></i>
            </button>
        </div>
        
        <form method="POST" action="" class="p-6 space-y-5">
            <input type="hidden" name="action" value="create_category">
            
            <div>
                <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-widest mb-2">// Category Display Name</label>
                <input type="text" id="add_category_name" name="category_name" oninput="liveSlugBuilder('add_category_name', 'add_category_slug')" placeholder="e.g. Full-Stack Web Apps" required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-xs font-medium text-white focus:outline-none focus:border-nftAccentCyan transition-colors">
            </div>

            <div>
                <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-widest mb-2">// Calculated Live URL Slug</label>
                <div class="relative">
                    <input type="text" id="add_category_slug" name="slug" placeholder="full-stack-web-apps" readonly required class="w-full bg-slate-900/40 border border-slate-800/60 rounded-xl px-4 py-3 text-xs font-mono text-nftAccentCyan focus:outline-none cursor-not-allowed select-none">
                    <span class="absolute right-4 top-3 text-[10px] uppercase font-bold tracking-widest text-slate-600 font-sans">Auto-Generated</span>
                </div>
            </div>

            <div>
                <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-widest mb-2">// Category Details / Description</label>
                <textarea id="add_category_details" name="category_details" rows="3" placeholder="Describe the structural cataloging architecture of this sector..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-xs font-medium text-white focus:outline-none focus:border-nftAccentCyan transition-colors resize-none"></textarea>
            </div>

            <div class="pt-2">
                <button type="submit" class="w-full btn-gradient py-3.5 rounded-xl text-xs font-bold tracking-widest uppercase text-white shadow-lg transition-all hover:scale-[1.01] active:scale-[0.99]">
                    Commit Category Record
                </button>
            </div>
        </form>
    </div>
</div>

<div id="updateCategoryModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm hidden p-4 transition-all duration-300">
    <div class="w-full max-w-md bg-nftDark border border-slate-800/80 rounded-2xl shadow-2xl shadow-black/80 overflow-hidden relative transform transition-all">
        <div class="p-6 border-b border-slate-900 flex items-center justify-between bg-slate-950/40">
            <h3 class="text-lg font-bold tracking-wide text-white flex items-center">
                <i class="fa-solid fa-pen-to-square mr-2.5 text-nftAccentPurple"></i> Update Selected Category
            </h3>
            <button onclick="closeModal('updateCategoryModal')" class="w-8 h-8 rounded-lg bg-slate-950 flex items-center justify-center border border-slate-800 text-nftTextGray hover:text-white transition-colors">
                <i class="fa-solid fa-xmark text-sm"></i>
            </button>
        </div>
        
        <form method="POST" action="" class="p-6 space-y-5">
            <input type="hidden" name="action" value="update_category">
            <input type="hidden" id="update_category_id" name="category_id">
            
            <div>
                <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-widest mb-2">// Modify Category Name</label>
                <input type="text" id="update_category_name" name="category_name" oninput="liveSlugBuilder('update_category_name', 'update_category_slug')" required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-xs font-medium text-white focus:outline-none focus:border-nftAccentPurple transition-colors">
            </div>

            <div>
                <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-widest mb-2">// Re-Computed Target Slug</label>
                <div class="relative">
                    <input type="text" id="update_category_slug" name="slug" readonly required class="w-full bg-slate-900/40 border border-slate-800/60 rounded-xl px-4 py-3 text-xs font-mono text-nftAccentPurple focus:outline-none cursor-not-allowed select-none">
                    <span class="absolute right-4 top-3 text-[10px] uppercase font-bold tracking-widest text-slate-600 font-sans">Synced</span>
                </div>
            </div>

            <div>
                <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-widest mb-2">// Modify Details / Description</label>
                <textarea id="update_category_details" name="category_details" rows="3" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-xs font-medium text-white focus:outline-none focus:border-nftAccentPurple transition-colors resize-none"></textarea>
            </div>

            <div class="pt-2">
                <button type="submit" class="w-full bg-gradient-to-r from-nftAccentPurple to-purple-700 py-3.5 rounded-xl text-xs font-bold tracking-widest uppercase text-white shadow-lg transition-all hover:scale-[1.01] active:scale-[0.99]">
                    Apply Changes & Sync
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    /**
     * Programmatic String RegEx Watcher Layer:
     * Converts raw text user keystrokes into url-compliant hyphenated string tokens
     */
    function liveSlugBuilder(sourceId, targetId) {
        const sourceElement = document.getElementById(sourceId);
        const targetElement = document.getElementById(targetId);
        
        if (sourceElement && targetElement) {
            let processedString = sourceElement.value;
            processedString = processedString
                .toLowerCase()
                .trim()
                .replace(/[^\w\s-]/g, '')     // Evacuate non-alphanumeric symbols
                .replace(/[\s_-]+/g, '-')     // Standardize empty whitespace clusters into clean hyphens
                .replace(/^-+|-+$/g, '');     // Purge out loose trailing string hyphens safely
                
            targetElement.value = processedString;
        }
    }

    // Modal Control Orchestrators
    function openModal(modalId) {
        const modalContainer = document.getElementById(modalId);
        if (modalContainer) {
            modalContainer.classList.remove('hidden');
            if(modalId === 'addCategoryModal') {
                setTimeout(() => document.getElementById('add_category_name').focus(), 50);
            }
        }
    }

    function closeModal(modalId) {
        const modalContainer = document.getElementById(modalId);
        if (modalContainer) {
            modalContainer.classList.add('hidden');
        }
    }

    // Capture Table Dataset Array Properties into Modal Form Targets
    function triggerUpdateContext(id, name, slug, details) {
        const idField = document.getElementById('update_category_id');
        const nameField = document.getElementById('update_category_name');
        const slugField = document.getElementById('update_category_slug');
        const detailsField = document.getElementById('update_category_details');
        
        if (idField && nameField && slugField && detailsField) {
            idField.value = id;
            nameField.value = name;
            slugField.value = slug;
            detailsField.value = details;
            openModal('updateCategoryModal');
            setTimeout(() => nameField.focus(), 50);
        }
    }

    // Retain sidebar mobile sync logic safely
    const navBarSidebar = document.getElementById('sidebar-nav-container');
    const overlayNavBackdrop = document.getElementById('sidebar-backdrop');
    
    if (navBarSidebar && overlayNavBackdrop) {
        const trackingConfigurationObserver = new MutationObserver(() => {
            if (!navBarSidebar.classList.contains('-translate-x-full')) {
                overlayNavBackdrop.classList.remove('hidden');
            } else {
                overlayNavBackdrop.classList.add('hidden');
            }
        });
        trackingConfigurationObserver.observe(navBarSidebar, { attributes: true, attributeFilter: ['class'] });
    }
</script>

</body>
</html>