<?php

/**
 * Visit Controller
 *
 * This file is used to register all actions for the Visit Controller.
 *
 * @since 1.0.0
 */

namespace LinkFiliate\App\Controllers;

if (! defined('ABSPATH')) {
    exit;
}

use LinkFiliate\App\Models\Clicks as ClickModel;
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;
use LinkFiliate\Libs\Utils\Cache;

class Clicklog
{


    /**
     * Get All Visit.
     */
    public function get_all(\WP_REST_Request $request)
    {
        // ✅ Validate nonce
        $nonce = $request->get_header('X-WP-Nonce');
        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            return new \WP_REST_Response(['status' => 'error', 'message' => 'Invalid nonce'], 403);
        }

        $clicks = new ClickModel();
        $result = $clicks->get_all();
        $tableData = [];

        foreach ($result as $l) {
            $ld = json_decode(json_encode($l));
            $server_data = [
                'REMOTE_ADDR'    => sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'] ?? '')),
                'HTTP_USER_AGENT'=> sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'] ?? '')),
                'REQUEST_URI'    => sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'] ?? '')),
            ];

            $clientHints = ClientHints::factory($server_data);

            /**
             * =============================
             * ✅ Device Info (cached by UA)
             * =============================
             */
            $ua_cache_key = 'device_' . md5($ld->user_agent);
            $deviceInfo = Cache::get_cache($ua_cache_key);

            if ($deviceInfo === false) {
                $dd = new DeviceDetector($ld->user_agent, $clientHints);
                $dd->parse();
                $browserNamesToCodes = array_flip(\DeviceDetector\Parser\Client\Browser::getAvailableBrowsers());
                $osNamesToCodes = array_flip(\DeviceDetector\Parser\OperatingSystem::getAvailableOperatingSystems());

                if ($dd->isBot()) {
                    $botInfo = $dd->getBot();
                    $deviceInfo = [
                        'type'     => 'bot',
                        'name'     => $botInfo['name'] ?? 'Unknown Bot',
                        'category' => $botInfo['category'] ?? 'Unknown'
                    ];
                } else {
                    $clientInfo = $dd->getClient() ?: [];
                    $osInfo     = $dd->getOs() ?: [];
                    $browserName = isset($clientInfo['name']) && isset($browserNamesToCodes[$clientInfo['name']])
                        ? $browserNamesToCodes[$clientInfo['name']]
                        : 'Unknown';
                    $osName = isset($osInfo['name']) && isset($osNamesToCodes[$osInfo['name']])
                        ? $osNamesToCodes[$osInfo['name']]
                        : 'Unknown';

                    $deviceInfo = [
                        'type'            => 'human',
                        'browser'         => $browserName,
                        'browser_version' => $clientInfo['version'] ?? 'Unknown',
                        'os'              => $osName,
                        'os_version'      => $osInfo['version'] ?? 'Unknown',
                        'device'          => $dd->getDeviceName() ?? 'Unknown',
                        'brand'           => $dd->getBrandName() ?? 'Unknown',
                        'model'           => $dd->getModel() ?? 'Unknown'
                    ];
                }

                // Cache for 7 days
                Cache::set_cache($ua_cache_key, $deviceInfo, 7 * DAY_IN_SECONDS);
            }


            /**
             * =============================
             * Row Data
             * =============================
             */
            $rowData = [
                'date'        => $ld->created_at,
                'clickId'     => $ld->id,
                'campaign_id'   => $ld->campaign_id,
                'campaign_name' => $ld->campaign_name,
                'ip_address'  => $ld->ip_address,
                'device_info' => $deviceInfo,
                'referer' =>$ld->referrer,
                'host' =>$ld->host,
                'uri' =>$ld->uri,

            ];


            $tableData[] = $rowData;
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'data'   => $tableData
        ], 200);
    }
}
