<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';

require_admin();

$pageTitle = 'Categories';
$success = '';
$error = '';

$editCategory = null;

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];

    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editCategory = $stmt->fetch();

    if (!$editCategory) {
        $error = 'Category not found.';
    }
}

if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category_id = ?");
    $stmt->execute([$deleteId]);
    $productCount = (int) $stmt->fetchColumn();

    if ($productCount > 0) {
        $error = 'This category cannot be deleted because products are assigned to it.';
    } else {
        $stmt = $pdo->prepare("SELECT name FROM categories WHERE id = ? LIMIT 1");
        $stmt->execute([$deleteId]);
        $deletedCategory = $stmt->fetch();

        $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
        $stmt->execute([$deleteId]);

        log_admin_activity(
            'category_deleted',
            'Category deleted: ' . ($deletedCategory['name'] ?? 'Category ID ' . $deleteId)
        );

        redirect(ADMIN_URL . '/categories.php?deleted=1');
    }
}

if (isset($_GET['deleted'])) {
    $success = 'Category deleted successfully.';
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $categoryId = (int) ($_POST['category_id'] ?? 0);
        $parentId = !empty($_POST['parent_id']) ? (int) $_POST['parent_id'] : null;
        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $seoTitle = trim($_POST['seo_title'] ?? '');
        $seoDescription = trim($_POST['seo_description'] ?? '');
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        $status = $_POST['status'] ?? 'active';

        if ($name === '') {
            $error = 'Category name is required.';
        } else {
            if ($slug === '') {
                $slug = generate_slug($name);
            } else {
                $slug = generate_slug($slug);
            }

            if ($categoryId > 0) {
                $check = $pdo->prepare("SELECT id FROM categories WHERE slug = ? AND id != ? LIMIT 1");
                $check->execute([$slug, $categoryId]);
            } else {
                $check = $pdo->prepare("SELECT id FROM categories WHERE slug = ? LIMIT 1");
                $check->execute([$slug]);
            }

            if ($check->fetch()) {
                $error = 'This category slug already exists. Please use another slug.';
            } else {
                if ($categoryId > 0) {
                    $stmt = $pdo->prepare("
                        UPDATE categories
                        SET parent_id = ?, name = ?, slug = ?, description = ?, seo_title = ?, seo_description = ?, sort_order = ?, status = ?
                        WHERE id = ?
                    ");

                    $stmt->execute([
                        $parentId,
                        $name,
                        $slug,
                        $description,
                        $seoTitle,
                        $seoDescription,
                        $sortOrder,
                        $status,
                        $categoryId
                    ]);

                    log_admin_activity(
                        'category_updated',
                        'Category updated: ' . $name . ' | Category ID: ' . $categoryId
                    );

                    redirect(ADMIN_URL . '/categories.php?updated=1');
                } else {
                    $stmt = $pdo->prepare("
                        INSERT INTO categories
                        (parent_id, name, slug, description, seo_title, seo_description, sort_order, status)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                   $stmt->execute([
    $parentId,
    $name,
    $slug,
    $description,
    $seoTitle,
    $seoDescription,
    $sortOrder,
    $status
]);

$newCategoryId = (int) $pdo->lastInsertId();

log_admin_activity(
    'category_created',
    'Category created: ' . $name . ' | Category ID: ' . $newCategoryId
);

redirect(ADMIN_URL . '/categories.php?created=1');
                }
            }
        }
    }
}

if (isset($_GET['created'])) {
    $success = 'Category created successfully.';
}

if (isset($_GET['updated'])) {
    $success = 'Category updated successfully.';
}

$categories = $pdo->query("
    SELECT c.*, p.name AS parent_name
    FROM categories c
    LEFT JOIN categories p ON c.parent_id = p.id
    ORDER BY c.sort_order ASC, c.id DESC
")->fetchAll();

$parentCategories = $pdo->query("
    SELECT id, name
    FROM categories
    WHERE status = 'active'
    ORDER BY name ASC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Categories</h1>
            <div class="admin-user">Create and manage product categories.</div>
        </div>

        <?php if ($editCategory): ?>
            <a href="<?= e(ADMIN_URL); ?>/categories.php" class="admin-btn admin-btn-light">Cancel Edit</a>
        <?php endif; ?>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel" style="margin-bottom: 24px;">
        <h2><?= $editCategory ? 'Edit Category' : 'Add New Category'; ?></h2>

        <form method="POST">
            <?= csrf_field(); ?>

            <input type="hidden" name="category_id" value="<?= e($editCategory['id'] ?? 0); ?>">

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Category Name *</label>
                    <input
                        type="text"
                        name="name"
                        value="<?= e($editCategory['name'] ?? ''); ?>"
                        required>
                </div>

                <div class="admin-field">
                    <label>Slug</label>
                    <input
                        type="text"
                        name="slug"
                        value="<?= e($editCategory['slug'] ?? ''); ?>"
                        placeholder="auto-generated if empty">
                </div>

                <div class="admin-field">
                    <label>Parent Category</label>
                    <select name="parent_id">
                        <option value="">No Parent</option>

                        <?php foreach ($parentCategories as $parent): ?>
                            <?php if ($editCategory && (int)$parent['id'] === (int)$editCategory['id']) continue; ?>

                            <option
                                value="<?= e($parent['id']); ?>"
                                <?= isset($editCategory['parent_id']) && (int)$editCategory['parent_id'] === (int)$parent['id'] ? 'selected' : ''; ?>>
                                <?= e($parent['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?= ($editCategory['status'] ?? '') === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?= ($editCategory['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Sort Order</label>
                    <input
                        type="number"
                        name="sort_order"
                        value="<?= e($editCategory['sort_order'] ?? 0); ?>">
                </div>

                <div class="admin-field">
                    <label>SEO Title</label>
                    <input
                        type="text"
                        name="seo_title"
                        value="<?= e($editCategory['seo_title'] ?? ''); ?>">
                </div>
            </div>

            <div class="admin-field">
                <label>SEO Description</label>
                <textarea name="seo_description"><?= e($editCategory['seo_description'] ?? ''); ?></textarea>
            </div>

            <div class="admin-field">
                <label>Description</label>
                <textarea name="description"><?= e($editCategory['description'] ?? ''); ?></textarea>
            </div>

            <button type="submit" class="admin-btn">
                <?= $editCategory ? 'Update Category' : 'Create Category'; ?>
            </button>
        </form>
    </section>

    <section class="admin-panel">
        <h2>All Categories</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Slug</th>
                    <th>Parent</th>
                    <th>Status</th>
                    <th>Sort</th>
                    <th>Created</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$categories): ?>
                    <tr>
                        <td colspan="7">No categories created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($categories as $category): ?>
                    <tr>
                        <td><?= e($category['name']); ?></td>
                        <td><?= e($category['slug']); ?></td>
                        <td><?= e($category['parent_name'] ?? '-'); ?></td>
                        <td><?= e(ucfirst($category['status'])); ?></td>
                        <td><?= e($category['sort_order']); ?></td>
                        <td><?= e(date('d M Y', strtotime($category['created_at']))); ?></td>
                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/categories.php?edit=<?= e($category['id']); ?>">Edit</a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/categories.php?delete=<?= e($category['id']); ?>"
                                onclick="return confirm('Are you sure you want to delete this category?');">
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

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