<?php
declare(strict_types=1);

namespace App\Modules\Fines\Models;

use App\Core\Model;
use App\Core\App;
use App\Core\Pagination;

class Violation extends Model
{
    protected static string $table = 'violations';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $dispatchEvents = true;

    protected static array $fillable = [
        'member_id', 'violation_date', 'description', 'reported_by', 'evidence_notes', 'status',
    ];

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['status'])) { $where .= ' AND v.status = ?'; $params[] = $filters['status']; }
        if (!empty($filters['search'])) {
            $where .= ' AND (m.full_name_ar LIKE ? OR v.description LIKE ?)';
            $s = '%' . $filters['search'] . '%'; $params[] = $s; $params[] = $s;
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM violations v JOIN members m ON m.id = v.member_id WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT v.*, m.full_name_ar as member_name, m.membership_number, e.full_name_ar as reported_by_name
             FROM violations v JOIN members m ON m.id = v.member_id LEFT JOIN employees e ON e.id = v.reported_by
             WHERE {$where} ORDER BY v.violation_date DESC LIMIT {$perPage} OFFSET {$offset}", $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}