
<?php 

class LogEvent extends Core {

    const LOGIN_ACCESS = 'LOGIN_ACCESS';
    const CREATE_PROCESS = 'CREATE_PROCESS';
    const CREATE_FILTERS = 'CREATE_FILTERS';
    const CREATE_TEST = 'CREATE_TEST';
    const CREATE_INTERVIEW = 'CREATE_INTERVIEW';
    const CREATE_REPORT_COMPATIBILITY = 'CREATE_REPORT_COMPATIBILITY';
    const CREATE_ANNOTATION = 'CREATE_ANNOTATION';
    const REMOVE_INTERVIEW = 'REMOVE_INTERVIEW';
    const APPLY_TEST = 'APPLY_TEST';
    const VIEW_CANDIDATES = 'VIEW_CANDIDATES';
    const REQUEST_FILLING_FILL = 'REQUEST_FILLING_FILL';
    const SEND_WHATSAPP = 'SEND_WHATSAPP';
    const SCORE_INTERVIEW = 'SCORE_INTERVIEW';
    const USE_FILTER = 'USE_FILTER';
    const LOGOUT = 'LOGOUT';
    const AI_PROCESS_CREATE = 'AI_PROCESS_CREATE';
    const AI_CREATIVE = 'AI_CREATIVE';
    const CREATIVE_SHARE_PDF = 'CREATIVE_SHARE_PDF';
    const CREATIVE_SHARE_STORY = 'CREATIVE_SHARE_STORY';
    const CREATIVE_SHARE_FEED = 'CREATIVE_SHARE_FEED';
    const ACCESS_SHARE_PROCESS = 'ACCESS_SHARE_PROCESS';
    const VIEW_SUGGESTION_CANDIDATES = 'VIEW_SUGGESTION_CANDIDATES';
    const KANBAN_CREATE_STEP_PROCESS = 'KANBAN_CREATE_STEP_PROCESS';
    const KANBAN_DELETE_STEP_PROCESS = 'KANBAN_DELETE_STEP_PROCESS';
    const VIEW_FIT_CULTURAL = 'VIEW_FIT_CULTURAL';
    const FILL_FIT_CULTURAL = 'FILL_FIT_CULTURAL';
    const VIEW_SHARED_FIT_CULTURAL = 'VIEW_SHARED_FIT_CULTURAL';
    const SHARED_CURRICULO = 'SHARED_CURRICULO';
    const DOWNLOAD_CURRICULO = 'DOWNLOAD_CURRICULO';
    const FINISH_PROCESS = 'FINISH_PROCESS';
    const APPROVE_PROCESS = 'APPROVE_PROCESS';

    public static function log(int $lead_id, int $resource_id, string $url, string $title, string $key, $is_candidate = false) {

        try {

            $env = parse_ini_file(__DIR__ . '/../.env');
            $client_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

            $stmt = parent::$conn->prepare("SELECT master_user FROM master_logins WHERE lead_id = :lead_id AND ip = :ip LIMIT 1");
            $stmt->execute([':ip' => $client_ip, ':lead_id' => $lead_id]);
            $master = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($master) {
                $title = "[Master][{$master['master_user']}] " . $title;
            }
            
            $stmt = parent::$conn->prepare("SELECT id FROM ip_addresses WHERE ip_address = :ip_address");
            $stmt->execute(['ip_address' => $client_ip]);
            $ip_record = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$ip_record) {
                $insert_stmt = parent::$conn->prepare("INSERT INTO ip_addresses (ip_address) VALUES (:ip_address)");
                $insert_stmt->execute(['ip_address' => $client_ip]);
                $ip_id = parent::$conn->lastInsertId();
            } else {
                $ip_id = $ip_record['id'];
            }

            $now = date('d/m/Y H:i');
            $params_value = [
                ':lead_id' => $lead_id,
                ':ip_id' => $ip_id,
                ':date_hit' => date('Y-m-d H:i:s'),
                ':country' => 'Brazil',
                ':region' => '',
                ':city' => '',
                ':url' => $env['APP_URL'] . $url,
                ':url_title' => $title,
                ':user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
                ':remote_host' => $client_ip,
                ':page_language' => 'pt-br'            
            ];

            $sql = "INSERT INTO page_hits (lead_id, ip_id, date_hit, country, region, city, url, url_title, user_agent, remote_host, page_language) 
                VALUES (:lead_id, :ip_id, :date_hit, :country, :region, :city, :url, :url_title, :user_agent, :remote_host, :page_language)";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute($params_value);

            if($is_candidate) {

                $sql = "SELECT id FROM leads WHERE id = :id LIMIT 1";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([':id' => $lead_id]);
                $lead = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($lead && isset($lead['id'])) {
                    LogEvent::logKpi(null, $lead['id'], $key);
                }

            } else {

                $sql = "SELECT company_id FROM companies_leads WHERE lead_id = :lead_id LIMIT 1";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([':lead_id' => $lead_id]);
                $company = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($company && isset($company['company_id'])) {
                    LogEvent::logKpi($company['company_id'], null, $key);
                }

            }
            
        } catch(\Exception $err) {
            file_put_contents('LOG_ERROR.txt', print_r($err, true));
        }

    }

    public static function logKpi($company_id = null, $candidate_id = null, $key = '') {   

        // Atualizar ou inserir o KPI
        $sql = "INSERT INTO kpi_stats (company_id, candidate_id, key_string, count) 
                VALUES (:company_id, :candidate_id, :key_string, 1)
                ON DUPLICATE KEY UPDATE count = count + 1";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':company_id' => $company_id,
            ':candidate_id' => $candidate_id,
            ':key_string' => $key
        ]);        

    }

}