<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class ApiLogs extends BaseController
{
    use ResponseTrait;
    
    protected $apiLogModel;
    
    public function __construct()
    {
        $this->apiLogModel = model('App\Models\ApiLogModel');
    }
    
    public function index()
    {
        $data = [
            'title' => 'API Logları',
        ];
        
        return view('admin/api_logs/index', $data);
    }
    
    public function getLogs()
    {
        $request = $this->request;
        
        $limit = $request->getGet('length') ?? 10;
        $start = $request->getGet('start') ?? 0;
        $search = $request->getGet('search')['value'] ?? '';
        
        $builder = $this->apiLogModel->builder();
        
        if (!empty($search)) {
            $builder->groupStart()
                ->like('uri', $search)
                ->orLike('request_body', $search)
                ->orLike('response_body', $search)
                ->orLike('ip_address', $search)
                ->groupEnd();
        }
        
        // Filtreleri uygula
        $startDate = $request->getGet('start_date');
        $endDate = $request->getGet('end_date');
        $errorOnly = $request->getGet('error_only');
        $userId = $request->getGet('user_id');
        $uri = $request->getGet('uri');
        
        if (!empty($startDate)) {
            $builder->where('request_time >=', $startDate . ' 00:00:00');
        }
        
        if (!empty($endDate)) {
            $builder->where('request_time <=', $endDate . ' 23:59:59');
        }
        
        if (!empty($errorOnly) && $errorOnly == '1') {
            $builder->where('response_code >=', 400);
        }
        
        if (!empty($userId)) {
            $builder->where('user_id', $userId);
        }
        
        if (!empty($uri)) {
            $builder->like('uri', $uri);
        }
        
        $totalRecords = $builder->countAllResults(false);
        
        $builder->orderBy('request_time', 'DESC');
        $logs = $builder->limit($limit, $start)->get()->getResultArray();
        
        return $this->respond([
            'draw' => $request->getGet('draw'),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalRecords,
            'data' => $logs
        ]);
    }
    
    public function view($id = null)
    {
        if ($id === null) {
            return redirect()->to('/admin/api-logs');
        }
        
        $log = $this->apiLogModel->find($id);
        
        if ($log === null) {
            return redirect()->to('/admin/api-logs')->with('error', 'Log kaydı bulunamadı');
        }
        
        // JSON verileri güzelce formatla
        if (!empty($log['request_headers'])) {
            $log['request_headers_formatted'] = json_encode(json_decode($log['request_headers']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        
        if (!empty($log['request_body'])) {
            $log['request_body_formatted'] = json_encode(json_decode($log['request_body']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        
        if (!empty($log['response_body'])) {
            $log['response_body_formatted'] = json_encode(json_decode($log['response_body']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        
        if (!empty($log['device_info'])) {
            $log['device_info_formatted'] = json_encode(json_decode($log['device_info']), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }
        
        $data = [
            'title' => 'API Log Detayı',
            'log' => $log
        ];
        
        return view('admin/api_logs/view', $data);
    }
    
    public function delete($id = null)
    {
        if ($id === null) {
            return redirect()->to('/admin/api-logs')->with('error', 'Silinecek log ID\'si belirtilmedi');
        }
        
        if ($this->apiLogModel->delete($id)) {
            return redirect()->to('/admin/api-logs')->with('success', 'Log kaydı başarıyla silindi');
        }
        
        return redirect()->to('/admin/api-logs')->with('error', 'Log kaydı silinemedi');
    }
    
    public function purge()
    {
        $daysToKeep = $this->request->getPost('days_to_keep') ?? 30;
        
        $date = date('Y-m-d H:i:s', strtotime("-$daysToKeep days"));
        
        $builder = $this->apiLogModel->builder();
        $deleted = $builder->where('request_time <', $date)->delete();
        
        return redirect()->to('/admin/api-logs')->with('success', "$deleted log kaydı başarıyla temizlendi");
    }
}