<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    private function checkVpn($ip, $service){
        switch($service){
            case 'ip-api':
                return VpnIpApi($ip);
            case 'proxycheck':
                $token = $this->data['setting']['proxycheck_key'] ?? '';
                return VpnProxyCheck($ip, $token);
            case 'iphub':
                $apiKey = $this->data['setting']['iphub_key'] ?? '';
                return VpnIpHub($ip, $apiKey);
            default:
                return false;
        }
    }

    public function login(){
        $UserModel = new UserModel();
        $ref = !empty($this->session->get('ref')) ? $this->session->get('ref') : NULL;
        $email = $this->request->getVar('email');
        $ip = $this->request->getIPAddress();
        
        $this->validation->setRules([
            'email' => 'required|valid_email'
        ]);

        if(!$this->validation->withRequest($this->request)->run()){
            $this->session->setFlashdata('msg', faucet_alert(validation_errors(), 'danger'));
            return redirect()->to(base_url('/'));
        }

        // VPN Check based on settings
        $vpnService = $this->data['setting']['vpn_service'] ?? '';
        $vpnEnabled = $this->data['setting']['vpn_check'] ?? '0';
        
        if($vpnEnabled == '1' && !empty($vpnService)){
            $isVpn = $this->checkVpn($ip, $vpnService);
            if($isVpn){
                $this->session->setFlashdata('msg', faucet_alert(['VPN/Proxy detected. Access denied.'], 'danger'));
                return redirect()->to(base_url('/'));
            }
        }

        // Check if user exists
        $user = $UserModel->getUser($email);
        
        if(empty($user)){
            // Register new user
            $userId = $UserModel->RegisterUser($email, $ip, $ref);
            if($userId){
                $user = $UserModel->getUser($email);
            } else {
                $this->session->setFlashdata('msg', faucet_alert(['Registration failed. Please try again.'], 'danger'));
                return redirect()->to(base_url('/'));
            }
        } else {
            // Update last active for existing user
            $UserModel->update($user['id'], ['last_active' => date('Y-m-d H:i:s')]);
            $this->session->setFlashdata('msg', faucet_alert(['Welcome back!'], 'success'));
        }

        // Set user session data
        $this->session->set([
            'user_id' => $user['id'],
            'user_ip' => $user['ip'],
            'logged_in' => true
        ]);

        return redirect()->to(base_url('/member/dashboard'));
    }

    public function logout(){
        $this->session->destroy();
        return redirect()->to(base_url('/'));
    }
}