<?php
declare(strict_types=1);

namespace App\Modules\Audit\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Audit\Models\AuditTrail;

class AuditController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'employee_id' => $request->get('employee_id', ''),
            'action'      => $request->get('action', ''),
            'entity_type' => $request->get('entity_type', ''),
            'date_from'   => $request->get('date_from', ''),
            'date_to'     => $request->get('date_to', ''),
            'search'      => trim((string) $request->get('q', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = AuditTrail::search($filters, 30, $page);

        $actions = AuditTrail::getDistinctActions();
        $entityTypes = AuditTrail::getDistinctEntityTypes();

        $db = App::getInstance()->db();
        $employees = $db->select("SELECT id, full_name_ar FROM employees WHERE is_archived = 0 ORDER BY full_name_ar");

        return $this->view('Audit.Views.index', [
            'rows'        => $result['data'],
            'pagination'  => $result['pagination'],
            'filters'     => $filters,
            'actions'     => $actions,
            'entityTypes' => $entityTypes,
            'employees'   => $employees,
        ]);
    }

    public function entityHistory(Request $request, string $type, string $id): Response
    {
        $history = AuditTrail::getEntityHistory($type, (int) $id);

        return $this->view('Audit.Views.entity-history', [
            'entityType' => $type,
            'entityId'   => (int) $id,
            'history'    => $history,
        ]);
    }
}