<?php

namespace Modules\Audit\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Security;

class AuditController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('audit_logs_view');

        $db = Database::getInstance();
        $userId = $this->request->get('user_id', '');
        $action = $this->request->get('action', '');
        $tableName = $this->request->get('table_name', '');
        $fromDate = $this->request->get('from_date', '');
        $toDate = $this->request->get('to_date', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('audit_logs al')
            ->select('al.*, u.first_name, u.last_name')
            ->leftJoin('users u', 'al.user_id', '=', 'u.id');

        if (!empty($userId)) {
            $query->where('al.user_id', $userId);
        }

        if (!empty($action)) {
            $query->where('al.action', $action);
        }

        if (!empty($tableName)) {
            $query->where('al.table_name', $tableName);
        }

        if (!empty($fromDate)) {
            $query->where('al.created_at', '>=', $fromDate . ' 00:00:00');
        }

        if (!empty($toDate)) {
            $query->where('al.created_at', '<=', $toDate . ' 23:59:59');
        }

        $logs = $query->orderBy('al.created_at', 'DESC')->paginate($perPage, $page);

        $users = $db->table('users')
            ->where('status', 'active')
            ->orderBy('first_name', 'ASC')
            ->get();

        $distinctActions = $db->table('audit_logs')
            ->select('DISTINCT action')
            ->orderBy('action', 'ASC')
            ->get();

        $distinctTables = $db->table('audit_logs')
            ->select('DISTINCT table_name')
            ->whereNotNull('table_name')
            ->orderBy('table_name', 'ASC')
            ->get();

        $this->view('Audit/index', [
            'title' => 'Audit Logs',
            'breadcrumb' => ['Audit Logs' => url('audit/logs')],
            'logs' => $logs,
            'users' => $users,
            'distinctActions' => $distinctActions,
            'distinctTables' => $distinctTables,
            'userId' => $userId,
            'action' => $action,
            'tableName' => $tableName,
            'fromDate' => $fromDate,
            'toDate' => $toDate,
        ]);
    }

    public function show(int $id): void
    {
        $this->requirePermission('audit_logs_view');

        $db = Database::getInstance();
        $log = $db->table('audit_logs al')
            ->select('al.*, u.first_name, u.last_name')
            ->leftJoin('users u', 'al.user_id', '=', 'u.id')
            ->where('al.id', $id)
            ->first();

        if (!$log) {
            $this->redirectWith(url('audit/logs'), 'error', 'Audit log not found.');
        }

        $oldValues = $log->old_values ? json_decode($log->old_values, true) : null;
        $newValues = $log->new_values ? json_decode($log->new_values, true) : null;

        $this->view('Audit/index', [
            'title' => 'Audit Log Detail',
            'breadcrumb' => [
                'Audit Logs' => url('audit/logs'),
                'Detail' => url('audit/logs/' . $id),
            ],
            'log' => $log,
            'oldValues' => $oldValues,
            'newValues' => $newValues,
        ]);
    }

    public function activity(): void
    {
        $this->requirePermission('audit_activity_view');

        $db = Database::getInstance();
        $userId = $this->request->get('user_id', '');
        $action = $this->request->get('action', '');
        $fromDate = $this->request->get('from_date', '');
        $toDate = $this->request->get('to_date', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('activity_logs al')
            ->select('al.*, u.first_name, u.last_name')
            ->leftJoin('users u', 'al.user_id', '=', 'u.id');

        if (!empty($userId)) {
            $query->where('al.user_id', $userId);
        }

        if (!empty($action)) {
            $query->where('al.action', $action);
        }

        if (!empty($fromDate)) {
            $query->where('al.created_at', '>=', $fromDate . ' 00:00:00');
        }

        if (!empty($toDate)) {
            $query->where('al.created_at', '<=', $toDate . ' 23:59:59');
        }

        $logs = $query->orderBy('al.created_at', 'DESC')->paginate($perPage, $page);

        $users = $db->table('users')
            ->where('status', 'active')
            ->orderBy('first_name', 'ASC')
            ->get();

        $this->view('Audit/activity', [
            'title' => 'Activity Logs',
            'breadcrumb' => ['Activity Logs' => url('audit/activity')],
            'logs' => $logs,
            'users' => $users,
            'userId' => $userId,
            'action' => $action,
            'fromDate' => $fromDate,
            'toDate' => $toDate,
        ]);
    }
}
