<?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 export(Request $request): Response
    {
        $db = App::getInstance()->db();

        $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', '')),
        ];

        $where = '1=1';
        $params = [];
        if (!empty($filters['employee_id'])) { $where .= ' AND a.employee_id = ?'; $params[] = (int) $filters['employee_id']; }
        if (!empty($filters['action'])) { $where .= ' AND a.action = ?'; $params[] = $filters['action']; }
        if (!empty($filters['entity_type'])) { $where .= ' AND a.entity_type = ?'; $params[] = $filters['entity_type']; }
        if (!empty($filters['date_from'])) { $where .= ' AND a.created_at >= ?'; $params[] = $filters['date_from'] . ' 00:00:00'; }
        if (!empty($filters['date_to'])) { $where .= ' AND a.created_at <= ?'; $params[] = $filters['date_to'] . ' 23:59:59'; }
        if (!empty($filters['search'])) {
            $where .= ' AND (a.entity_label LIKE ? OR a.employee_name LIKE ? OR a.notes LIKE ?)';
            $s = '%' . $filters['search'] . '%'; $params[] = $s; $params[] = $s; $params[] = $s;
        }

        $rows = $db->select(
            "SELECT a.created_at, a.employee_name, a.action, a.entity_type, a.entity_label, a.notes, a.ip_address
             FROM audit_trail a WHERE {$where} ORDER BY a.created_at DESC LIMIT 10000",
            $params
        );

        $filename = 'audit_log_' . date('Y-m-d_His') . '.csv';

        $response = new Response();
        $response->header('Content-Type', 'text/csv; charset=utf-8');
        $response->header('Content-Disposition', 'attachment; filename="' . $filename . '"');

        $output = "\xEF\xBB\xBF";
        $output .= "التاريخ,المستخدم,الإجراء,الوحدة,العنصر,الملاحظات,IP\n";

        foreach ($rows as $row) {
            $output .= '"' . str_replace('"', '""', $row['created_at'] ?? '') . '",';
            $output .= '"' . str_replace('"', '""', $row['employee_name'] ?? '') . '",';
            $output .= '"' . str_replace('"', '""', $row['action'] ?? '') . '",';
            $output .= '"' . str_replace('"', '""', $row['entity_type'] ?? '') . '",';
            $output .= '"' . str_replace('"', '""', $row['entity_label'] ?? '') . '",';
            $output .= '"' . str_replace('"', '""', $row['notes'] ?? '') . '",';
            $output .= '"' . str_replace('"', '""', $row['ip_address'] ?? '') . '"' . "\n";
        }

        return $response->html($output);
    }

    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,
        ]);
    }
}
