<?php

namespace Core\App\Controllers;

use Core\App\Models\CategoryModel;
use Core\App\Services\UploadService;
use Core\System\Request;
use Core\System\Response;

class CategoriesController
{
    protected CategoryModel $categories;
    protected UploadService $uploads;

    public function __construct()
    {
        $this->categories = new CategoryModel();
        $this->uploads = new UploadService(ROOT_PATH . '/uploads', '/uploads');
    }

    public function index()
    {
        view_admin('categories/index', ['categories' => $this->categories->getAll()]);
    }

    public function create()
    {
        view_admin('categories/create');
    }

    public function store()
    {
        $data = Request::input();
        if (empty($data['slug']) && !empty($data['name'])) {
            $data['slug'] = $this->makeSlug($data['name']);
        }
        $data['status'] = $data['status'] ?? 'active';

        if (!empty($_FILES['image']['name'])) {
            $data['image'] = $this->uploads->storeImage($_FILES['image'], 'categories');
        }

        $this->categories->create($data);
        Response::redirect('/admin/categories');
    }

    public function edit($id)
    {
        $item = $this->categories->getById((int) $id);
        if (!$item) {
            Response::redirect('/admin/categories');
            return;
        }

        view_admin('categories/edit', ['item' => $item]);
    }

    public function update($id)
    {
        $id = (int) $id;
        $data = Request::input();
        $current = $this->categories->getById($id);
        if (!$current) {
            Response::redirect('/admin/categories');
            return;
        }

        if (empty($data['slug']) && !empty($data['name'])) {
            $data['slug'] = $this->makeSlug($data['name']);
        }
        $data['status'] = $data['status'] ?? $current['status'];

        if (!empty($_FILES['image']['name'])) {
            $data['image'] = $this->uploads->storeImage($_FILES['image'], 'categories');
            $this->uploads->deleteByWebPath($current['image'] ?? null);
        } else {
            $data['image'] = $current['image'];
        }

        $this->categories->update($id, $data);
        Response::redirect('/admin/categories');
    }

    public function delete($id)
    {
        if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
            http_response_code(405);
            exit('Method Not Allowed');
        }

        $item = $this->categories->getById((int) $id);
        if ($item) {
            $this->uploads->deleteByWebPath($item['image'] ?? null);
        }

        $this->categories->delete((int) $id);
        Response::redirect('/admin/categories');
    }

    private function makeSlug(string $text): string
    {
        $text = trim($text);
        $text = mb_strtolower($text, 'UTF-8');
        $text = preg_replace('/[^a-z0-9\u0600-\u06FF]+/u', '-', $text);
        return trim($text, '-');
    }
}
