<?php

namespace App\Controllers\Owner;

use App\Controllers\BaseController;
use App\Models\ProductCategoryModel;
use App\Models\ProductModel;

class Category extends BaseController
{
    protected $category;
    protected ProductModel $product;

    public function __construct()
    {
        $this->category = new ProductCategoryModel();
        $this->product = new ProductModel();
    }

    public function index()
    {
        $keyword = trim((string) $this->request->getGet('keyword'));
        $sort = (string) $this->request->getGet('sort');

        $categoriesQuery = $this->category
            ->select('categories.id_category, categories.nama_kategori, COUNT(products.id_product) AS total_products')
            ->join('products', 'products.id_category = categories.id_category', 'left')
            ->groupBy('categories.id_category, categories.nama_kategori');

        if ($keyword !== '') {
            $categoriesQuery->like('categories.nama_kategori', $keyword);
        }

        switch ($sort) {
            case 'name_asc':
                $categoriesQuery->orderBy('categories.nama_kategori', 'ASC');
                break;
            case 'name_desc':
                $categoriesQuery->orderBy('categories.nama_kategori', 'DESC');
                break;
            case 'products_high':
                $categoriesQuery->orderBy('total_products', 'DESC')->orderBy('categories.nama_kategori', 'ASC');
                break;
            default:
                $categoriesQuery->orderBy('categories.id_category', 'DESC');
                $sort = 'latest';
                break;
        }

        $categories = $categoriesQuery->findAll();

        $summary = \Config\Database::connect()
            ->table('categories')
            ->select('COUNT(DISTINCT categories.id_category) AS total_categories, COUNT(products.id_product) AS total_products', false)
            ->join('products', 'products.id_category = categories.id_category', 'left')
            ->get()
            ->getRowArray();
        $totalCategories = (int) ($summary['total_categories'] ?? 0);
        $totalProducts = (int) ($summary['total_products'] ?? 0);

        $data = [
            'title' => 'Kategori Barang',
            'categories' => $categories,
            'keyword' => $keyword,
            'sort' => $sort,
            'totalCategories' => $totalCategories,
            'totalProducts' => $totalProducts,
            'averageProducts' => $totalCategories > 0 ? $totalProducts / $totalCategories : 0,
        ];

        return view('owner/category/index', $data);
    }

    public function create()
    {
        return view('owner/category/create', [
            'title' => 'Tambah Kategori'
        ]);
    }

    public function store()
    {
        if (! $this->validateCategory()) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->category->insert([
            'nama_kategori' => trim((string) $this->request->getPost('nama_kategori'))
        ]);

        return redirect()->to('/owner/category')
            ->with('success', 'Kategori berhasil ditambahkan');
    }

    public function edit($id)
    {
        $category = $this->category->find($id);
        if (! $category) {
            return redirect()->to('/owner/category')->with('error', 'Kategori tidak ditemukan.');
        }

        $data = [
            'title' => 'Edit Kategori',
            'category' => $category
        ];

        return view('owner/category/edit', $data);
    }

    public function update($id)
    {
        if (! $this->category->find($id)) {
            return redirect()->to('/owner/category')->with('error', 'Kategori tidak ditemukan.');
        }

        if (! $this->validateCategory((int) $id)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->category->update($id, [
            'nama_kategori' => trim((string) $this->request->getPost('nama_kategori'))
        ]);

        return redirect()->to('/owner/category')
            ->with('success', 'Kategori berhasil diupdate');
    }

    public function delete($id)
    {
        if (! $this->request->is('post')) {
            return $this->response->setStatusCode(405);
        }

        $category = $this->category->find($id);
        if (! $category) {
            return redirect()->to('/owner/category')->with('error', 'Kategori tidak ditemukan.');
        }

        $usedByProducts = $this->product
            ->where('id_category', $id)
            ->countAllResults();
        if ($usedByProducts > 0) {
            return redirect()->to('/owner/category')->with('error', 'Kategori tidak dapat dihapus karena masih digunakan oleh produk.');
        }

        $this->category->delete($id);

        return redirect()->to('/owner/category')
            ->with('success', 'Kategori berhasil dihapus');
    }

    private function validateCategory(?int $id = null): bool
    {
        $uniqueRule = 'is_unique[categories.nama_kategori]';
        if ($id !== null) {
            $uniqueRule = 'is_unique[categories.nama_kategori,id_category,' . $id . ']';
        }

        return $this->validate([
            'nama_kategori' => 'required|min_length[2]|max_length[100]|' . $uniqueRule,
        ]);
    }
}
