<?php

namespace Modules\Services\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Session;
use core\Security;

class CategoryController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('services_view');

        $this->view('Services/categories', [
            'title' => 'Service Categories',
            'breadcrumb' => [
                'Services' => url('services'),
                'Categories' => url('services/categories'),
            ],
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('services_create');

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'description' => 'max_length:1000',
            'sort_order' => 'integer|min:0',
            'is_active' => 'in:0,1',
        ]);

        $db = Database::getInstance();

        $slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $validated['name']), '-'));
        $existing = $db->table('service_categories')->where('slug', 'LIKE', $slug . '%')->count();
        if ($existing > 0) {
            $slug .= '-' . $existing;
        }

        $categoryId = $db->table('service_categories')->insert([
            'name' => $validated['name'],
            'slug' => $slug,
            'description' => $validated['description'] ?? null,
            'sort_order' => $validated['sort_order'] ?? 0,
            'is_active' => $validated['is_active'] ?? 1,
            'created_at' => date(DATE_TIME_FORMAT),
            'updated_at' => date(DATE_TIME_FORMAT),
        ]);

        $this->logActivity('create', 'Created service category: ' . $validated['name']);
        $this->logAudit('create', 'service_categories', $categoryId, null, $validated);

        $this->success(['id' => $categoryId], 'Category created successfully.');
    }

    public function update(int $id): void
    {
        $this->requirePermission('services_edit');

        $db = Database::getInstance();
        $category = $db->table('service_categories')->find($id);
        if (!$category) {
            $this->error('Category not found.', 404);
        }

        $oldValues = (array)$category;

        $validated = $this->validate([
            'name' => 'required|max_length:255',
            'description' => 'max_length:1000',
            'sort_order' => 'integer|min:0',
            'is_active' => 'in:0,1',
        ]);

        $updateData = [
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'sort_order' => $validated['sort_order'] ?? 0,
            'is_active' => $validated['is_active'] ?? 0,
            'updated_at' => date(DATE_TIME_FORMAT),
        ];

        if ($validated['name'] !== $category->name) {
            $slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $validated['name']), '-'));
            $existing = $db->table('service_categories')
                ->where('slug', 'LIKE', $slug . '%')
                ->where('id', '!=', $id)
                ->count();
            if ($existing > 0) {
                $slug .= '-' . $existing;
            }
            $updateData['slug'] = $slug;
        }

        $db->table('service_categories')
            ->where('id', $id)
            ->update($updateData);

        $this->logActivity('update', 'Updated service category: ' . $validated['name']);
        $this->logAudit('update', 'service_categories', $id, $oldValues, $validated);

        $this->success(null, 'Category updated successfully.');
    }

    public function delete(int $id): void
    {
        $this->requirePermission('services_delete');

        $db = Database::getInstance();
        $category = $db->table('service_categories')->find($id);
        if (!$category) {
            $this->error('Category not found.', 404);
        }

        $servicesCount = $db->table('services')
            ->where('category_id', $id)
            ->where('deleted_at', 'IS', null)
            ->count();

        if ($servicesCount > 0) {
            $this->error('Cannot delete category with ' . $servicesCount . ' associated services.');
        }

        $db->table('service_categories')
            ->where('id', $id)
            ->update([
                'deleted_at' => date(DATE_TIME_FORMAT),
            ]);

        $this->logActivity('delete', 'Deleted service category: ' . $category->name);
        $this->logAudit('delete', 'service_categories', $id, (array)$category, null);

        $this->success(null, 'Category deleted successfully.');
    }
}
