<?php
declare(strict_types=1);

namespace App\Modules\Fines\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Modules\Fines\Models\Violation;

class ViolationController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'search' => trim((string) $request->get('q', '')),
            'status' => $request->get('status', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = Violation::search($filters, 25, $page);

        return $this->view('Fines.Views.violations.index', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function create(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) return $this->redirect('/members')->withError('العضو غير موجود');

        return $this->view('Fines.Views.violations.create', ['member' => $member]);
    }

    public function store(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) return $this->redirect('/members')->withError('العضو غير موجود');

        $description = trim((string) $request->post('description', ''));
        $violationDate = $request->post('violation_date', date('Y-m-d'));
        $evidence = trim((string) $request->post('evidence_notes', ''));

        if ($description === '') return $this->redirect("/violations/create/{$memberId}")->withError('وصف المخالفة مطلوب');

        $employee = App::getInstance()->currentEmployee();

        $violation = Violation::create([
            'member_id'      => (int) $memberId,
            'violation_date' => $violationDate,
            'description'    => $description,
            'reported_by'    => $employee ? (int) $employee->id : null,
            'evidence_notes' => $evidence ?: null,
            'status'         => 'reported',
        ]);

        EventBus::dispatch('violation.reported', ['violation_id' => (int) $violation->id, 'member_id' => (int) $memberId]);

        return $this->redirect('/violations')->withSuccess('تم تسجيل المخالفة');
    }
}