<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\PostCategory;
use App\Models\AuditLog;

class PostCategoryController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $model = new PostCategory();
        $categories = $model->all();
        foreach ($categories as $cat) {
            $cat->post_count = $model->getPostCount($cat->id);
        }
        $this->view('post_categories/index', ['categories' => $categories]);
    }

    public function create()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $this->view('post_categories/form');
    }

    public function store()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $model = new PostCategory();
        $slug = $this->createSlug($_POST['name'] ?? '');

        $existing = $model->findBySlug($slug);
        if ($existing) {
            $slug = $slug . '-' . uniqid();
        }

        $model->create([
            'name' => $_POST['name'] ?? '',
            'slug' => $slug,
            'description' => $_POST['description'] ?? '',
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'post_category.create', 'post_categories', $model->db->lastInsertId(), "Created category: {$_POST['name']}");

        $_SESSION['success'] = 'Category created successfully';
        $this->redirect('/post-categories');
    }

    public function edit($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $model = new PostCategory();
        $category = $model->find($params['id'] ?? null);
        if (!$category) {
            $_SESSION['error'] = 'Category not found';
            $this->redirect('/post-categories');
        }
        $this->view('post_categories/form', ['category' => $category]);
    }

    public function update($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $id = $params['id'] ?? null;
        $model = new PostCategory();
        $category = $model->find($id);
        if (!$category) {
            $_SESSION['error'] = 'Category not found';
            $this->redirect('/post-categories');
        }

        $model->update($id, [
            'name' => $_POST['name'] ?? '',
            'description' => $_POST['description'] ?? '',
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'post_category.update', 'post_categories', $id, "Updated category: {$_POST['name']}");

        $_SESSION['success'] = 'Category updated successfully';
        $this->redirect('/post-categories');
    }

    public function delete($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $id = $params['id'] ?? null;
        $model = new PostCategory();
        $category = $model->find($id);
        if ($category) {
            $audit = new AuditLog();
            $audit->log(Auth::id(), 'post_category.delete', 'post_categories', $id, "Deleted category: {$category->name}");
            $model->delete($id);
            $_SESSION['success'] = 'Category deleted';
        }
        $this->redirect('/post-categories');
    }

    private function createSlug($string)
    {
        $string = preg_replace('/[^a-zA-Z0-9\s-]/', '', $string);
        $string = preg_replace('/[\s_]+/', '-', $string);
        $string = preg_replace('/-+/', '-', $string);
        return strtolower(trim($string, '-'));
    }
}
