<?php

namespace App\Modules\Discipline\Controllers;

use App\Core\BaseApiController;
use App\Modules\Discipline\Models\ViolationCategoryModel;
use App\Modules\Discipline\Models\ViolationModel;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Master data pelanggaran (kategori + item).
 * Biasanya diakses ADMIN / BK.
 */
class ViolationController extends BaseApiController
{
    public function index(): ResponseInterface
    {
        $categoryModel  = new ViolationCategoryModel();
        $violationModel = new ViolationModel();

        $categories = $categoryModel->orderBy('code', 'ASC')->findAll();
        $violations = $violationModel
            ->where('is_active', 1)
            ->orderBy('category_id', 'ASC')
            ->orderBy('score', 'DESC')
            ->findAll();

        // Group violations per category
        $byCategory = [];
        foreach ($categories as $cat) {
            $byCategory[$cat['id']] = [
                'id'          => (int) $cat['id'],
                'code'        => $cat['code'],
                'name'        => $cat['name'],
                'description' => $cat['description'],
                'items'       => [],
            ];
        }

        foreach ($violations as $v) {
            $cid = (int) $v['category_id'];
            if (! isset($byCategory[$cid])) {
                continue;
            }
            $byCategory[$cid]['items'][] = [
                'id'          => (int) $v['id'],
                'code'        => $v['code'],
                'title'       => $v['title'],
                'description' => $v['description'],
                'score'       => (int) $v['score'],
            ];
        }

        $out = array_values($byCategory);

        return $this->successResponse($out, 'Violation master data');
    }
}

