<?php
require_once 'config/database.php';

class AuditController {
    private $conn;

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection(); // returns PDO
    }

    public function logApiRequest($data) {
        try {
            $requiredFields = ['endpoint', 'method', 'request_payload', 'response_payload', 'status_code'];

            foreach ($requiredFields as $field) {
                if (!isset($data[$field])) {
                    return ["status" => "error", "message" => "Missing required field: $field"];
                }
            }

            $user_id = $data['user_id'] ?? null;
            $user_type = $data['user_type'] ?? null;
            $ip_address = $data['ip_address'] ?? ($_SERVER['REMOTE_ADDR'] ?? null);
            $user_agent = $data['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? null);

            // Normalize values
            $endpoint = is_string($data['endpoint']) ? $data['endpoint'] : json_encode($data['endpoint']);
            $method = is_string($data['method']) ? $data['method'] : json_encode($data['method']);
            $requestPayload = is_string($data['request_payload']) ? $data['request_payload'] : json_encode($data['request_payload']);
            $responsePayload = is_string($data['response_payload']) ? $data['response_payload'] : json_encode($data['response_payload']);
            $statusCode = is_numeric($data['status_code']) ? (int)$data['status_code'] : 0;

            $query = "INSERT INTO api_audit_logs 
                (user_id, user_type, endpoint, method, request_payload, response_payload, status_code, ip_address, user_agent)
                VALUES (:user_id, :user_type, :endpoint, :method, :request_payload, :response_payload, :status_code, :ip_address, :user_agent)";

            $stmt = $this->conn->prepare($query);
            $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindValue(':user_type', $user_type, PDO::PARAM_STR);
            $stmt->bindValue(':endpoint', $endpoint, PDO::PARAM_STR);
            $stmt->bindValue(':method', $method, PDO::PARAM_STR);
            $stmt->bindValue(':request_payload', $requestPayload, PDO::PARAM_STR);
            $stmt->bindValue(':response_payload', $responsePayload, PDO::PARAM_STR);
            $stmt->bindValue(':status_code', $statusCode, PDO::PARAM_INT);
            $stmt->bindValue(':ip_address', $ip_address, PDO::PARAM_STR);
            $stmt->bindValue(':user_agent', $user_agent, PDO::PARAM_STR);

            $stmt->execute();

            return ["status" => "success", "message" => "Audit log created successfully"];
        } catch (PDOException $e) {
            return ["status" => "error", "message" => "Database error: " . $e->getMessage()];
        }
    }

    public function getAuditLogs($filters = [], $page = 1, $limit = 20) {
        try {
            $query = "SELECT * FROM audit_trail WHERE 1=1";
            $params = [];

            if (!empty($filters['user_id'])) {
                $query .= " AND user_id = :user_id";
                $params[':user_id'] = $filters['user_id'];
            }

            if (!empty($filters['user_type'])) {
                $query .= " AND user_type = :user_type";
                $params[':user_type'] = $filters['user_type'];
            }

            if (!empty($filters['endpoint'])) {
                $query .= " AND endpoint LIKE :endpoint";
                $params[':endpoint'] = "%" . $filters['endpoint'] . "%";
            }

            if (!empty($filters['method'])) {
                $query .= " AND method = :method";
                $params[':method'] = $filters['method'];
            }

            if (!empty($filters['status_code'])) {
                $query .= " AND status_code = :status_code";
                $params[':status_code'] = $filters['status_code'];
            }

            if (!empty($filters['start_date'])) {
                $query .= " AND timestamp >= :start_date";
                $params[':start_date'] = $filters['start_date'];
            }

            if (!empty($filters['end_date'])) {
                $query .= " AND timestamp <= :end_date";
                $params[':end_date'] = $filters['end_date'];
            }

            $offset = ($page - 1) * $limit;
            $query .= " ORDER BY timestamp DESC LIMIT :offset, :limit";

            $stmt = $this->conn->prepare($query);

            // bind dynamic filters
            foreach ($params as $key => $val) {
                $stmt->bindValue($key, $val, is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
            }

            // bind pagination separately as integers
            $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
            $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);

            $stmt->execute();
            $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return [
                'status' => 'success',
                'data' => $logs,
                'message' => 'Audit logs retrieved successfully'
            ];
        } catch (PDOException $e) {
            return ['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
}
