<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Database;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Helpers\Paginator;
use PDO;

final class ActivityLogController extends BaseController
{
    public function index(Request $request): Response
    {
        $paginator = Paginator::fromRequest($request, defaultPerPage: 25);
        $category = $request->query('category');
        $search = $request->query('search');

        $conditions = ['1=1'];
        $bindings = [];

        if ($category && $category !== 'all') {
            $conditions[] = 'al.category = :category';
            $bindings['category'] = $category;
        }
        if ($search) {
            $conditions[] = 'al.action LIKE :search';
            $bindings['search'] = '%' . $search . '%';
        }

        $where = 'WHERE ' . implode(' AND ', $conditions);
        $pdo = Database::connection();

        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM activity_logs al {$where}");
        $countStmt->execute($bindings);
        $paginator->setTotal((int) $countStmt->fetchColumn());

        $sql = "SELECT al.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name
                FROM activity_logs al
                LEFT JOIN users u ON u.id = al.user_id
                {$where}
                ORDER BY al.created_at DESC
                LIMIT :limit OFFSET :offset";

        $stmt = $pdo->prepare($sql);
        foreach ($bindings as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->bindValue('limit', $paginator->perPage(), PDO::PARAM_INT);
        $stmt->bindValue('offset', $paginator->offset(), PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success(['rows' => $rows, 'meta' => $paginator->meta()]);
        }

        return $this->view('activity-logs/index', [
            'title' => 'Activity Logs',
            'activeNav' => 'activity-logs',
            'breadcrumbs' => [['Home', 'dashboard'], ['Administration', 'users'], ['Activity Logs', 'activity-logs']],
            'rows' => $rows,
            'meta' => $paginator->meta(),
        ]);
    }

    /** Login History — successful and failed attempts, powers a Security tab on Profile/Settings. */
    public function loginHistory(Request $request): Response
    {
        $paginator = Paginator::fromRequest($request, defaultPerPage: 25);
        $pdo = Database::connection();

        $scopeToSelf = !\App\Core\Rbac::can('user_management.view');
        $where = '';
        $bindings = [];

        if ($scopeToSelf) {
            $user = $this->currentUser();
            $where = 'WHERE la.email = :email';
            $bindings['email'] = $user['email'];
        }

        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM login_attempts la {$where}");
        $countStmt->execute($bindings);
        $paginator->setTotal((int) $countStmt->fetchColumn());

        $sql = "SELECT la.* FROM login_attempts la {$where} ORDER BY la.attempted_at DESC LIMIT :limit OFFSET :offset";
        $stmt = $pdo->prepare($sql);
        foreach ($bindings as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->bindValue('limit', $paginator->perPage(), PDO::PARAM_INT);
        $stmt->bindValue('offset', $paginator->offset(), PDO::PARAM_INT);
        $stmt->execute();

        return AjaxResponse::success(['rows' => $stmt->fetchAll(), 'meta' => $paginator->meta()]);
    }
}
