<?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, 40, $page);

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

        $db = App::getInstance()->db();
        $employees = [];
        try {
            $employees = $db->select("SELECT id, full_name_ar FROM employees WHERE is_archived = 0 ORDER BY full_name_ar");
        } catch (\Throwable $e) {}

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

    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $entry = $db->selectOne("SELECT * FROM audit_trail WHERE id = ?", [(int) $id]);
        if (!$entry) {
            return $this->redirect('/audit')->withError('السجل غير موجود');
        }

        $prevEntry = $db->selectOne(
            "SELECT id FROM audit_trail WHERE entity_type = ? AND entity_id = ? AND id < ? ORDER BY id DESC LIMIT 1",
            [$entry['entity_type'], $entry['entity_id'], (int) $id]
        );
        $nextEntry = $db->selectOne(
            "SELECT id FROM audit_trail WHERE entity_type = ? AND entity_id = ? AND id > ? ORDER BY id ASC LIMIT 1",
            [$entry['entity_type'], $entry['entity_id'], (int) $id]
        );

        return $this->view('Audit.Views.show', [
            'entry'  => $entry,
            'prevId' => $prevEntry ? (int) $prevEntry['id'] : null,
            'nextId' => $nextEntry ? (int) $nextEntry['id'] : null,
        ]);
    }

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

        $entityLabel = null;
        if (!empty($history)) {
            $entityLabel = $history[0]['entity_label'] ?? null;
        }

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