<?php
/**
 * AdminAuditLog Model
 * Maps to `admin_audit_logs` table
 * Dedicated audit trail for all admin actions
 */

require_once __DIR__ . '/../Core/Model.php';
require_once __DIR__ . '/../Helpers/Security.php';

class AdminAuditLog extends Model {
    protected string $table = 'admin_audit_logs';

    /**
     * Record an admin action
     */
    public function record(
        int $adminId,
        string $action,
        string $module,
        ?string $targetType = null,
        ?int $targetId = null,
        ?string $detail = null,
        string $result = 'success'
    ): void {
        $this->insert([
            'admin_id'    => $adminId,
            'action'      => $action,
            'module'      => $module,
            'target_type' => $targetType,
            'target_id'   => $targetId,
            'detail'      => $detail,
            'ip_address'  => Security::getClientIp(),
            'result'      => $result,
            'created_at'  => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * Get paginated admin audit logs with optional filters
     */
    public function getLogs(array $filters = [], int $limit = 30, int $offset = 0): array {
        [$whereSql, $params] = $this->buildConditions($filters);

        $sql = "SELECT aal.*, u.username as admin_username, u.first_name, u.last_name
                FROM `admin_audit_logs` aal
                LEFT JOIN `users` u ON aal.admin_id = u.id
                WHERE {$whereSql}
                ORDER BY aal.created_at DESC
                LIMIT :limit OFFSET :offset";

        $stmt = $this->db->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        $stmt->bindValue(':limit',  $limit,  PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function countLogs(array $filters = []): int {
        [$whereSql, $params] = $this->buildConditions($filters);
        $sql = "SELECT COUNT(*) FROM `admin_audit_logs` aal WHERE {$whereSql}";
        $stmt = $this->db->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        $stmt->execute();
        return (int)$stmt->fetchColumn();
    }

    private function buildConditions(array $filters): array {
        $conditions = ['1=1'];
        $params = [];

        if (!empty($filters['admin_id'])) {
            $conditions[] = 'aal.admin_id = :admin_id';
            $params[':admin_id'] = (int)$filters['admin_id'];
        }
        if (!empty($filters['module'])) {
            $conditions[] = 'aal.module = :module';
            $params[':module'] = $filters['module'];
        }
        if (!empty($filters['action'])) {
            $conditions[] = 'aal.action LIKE :action';
            $params[':action'] = '%' . $filters['action'] . '%';
        }
        if (!empty($filters['date_from'])) {
            $conditions[] = 'aal.created_at >= :date_from';
            $params[':date_from'] = $filters['date_from'] . ' 00:00:00';
        }
        if (!empty($filters['date_to'])) {
            $conditions[] = 'aal.created_at <= :date_to';
            $params[':date_to'] = $filters['date_to'] . ' 23:59:59';
        }
        if (!empty($filters['result'])) {
            $conditions[] = 'aal.result = :result';
            $params[':result'] = $filters['result'];
        }

        return [implode(' AND ', $conditions), $params];
    }
}
