<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class login extends MX_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('cookie');
        $this->load->library('form_validation');
    }

    public function index()
    {
        // Se já está logado, redireciona
        $admin = $this->session->userdata('admin');
        if (is_array($admin) && !empty($admin['id'])) {
            redirect('admin/dashboard');
            return;
        }

        $settings = $this->setting_model->get_setting();
        $data['page_title']       = lang('sign_in');
        $data['error']            = '';
        $data['turnstile_key']    = $settings->turnstile_site_key ?? '';
        $data['max_attempts']     = $settings->login_max_attempts ?? 5;

        if ($this->input->post('submitted')) {
            $username = trim($this->input->post('username'));
            $password = $this->input->post('password');
            $ip       = $this->input->ip_address();

            // 1. Verifica bloqueio por IP
            if ($this->_is_locked($ip, $username, $settings)) {
                $lockout = $settings->login_lockout_minutes ?? 15;
                $data['error'] = "Acesso bloqueado por tentativas excessivas. Tente novamente em {$lockout} minutos.";
                $this->load->view('login/login', $data);
                return;
            }

            // 2. Valida Turnstile
            $turnstile_token = $this->input->post('cf-turnstile-response');
            if (!empty($data['turnstile_key']) && !$this->_verify_turnstile($turnstile_token, $settings->turnstile_secret_key ?? '')) {
                $data['error'] = 'Verificação de segurança falhou. Tente novamente.';
                $this->load->view('login/login', $data);
                return;
            }

            if (empty($username) || empty($password)) {
                $data['error'] = lang('authenication_failed');
            } else {
                $result = $this->auth->login_admin($username, $password);
                if ($result) {
                    // Limpa tentativas ao logar com sucesso
                    $this->_clear_attempts($ip, $username);
                    // Atualiza last_login
                    $this->db->where('username', $username)
                             ->update('users', ['last_login' => date('Y-m-d H:i:s')]);
                    redirect('admin/dashboard');
                    return;
                } else {
                    // Registra tentativa falha
                    $this->_record_attempt($ip, $username);
                    $remaining = $this->_remaining_attempts($ip, $username, $settings);
                    if ($remaining <= 2 && $remaining > 0) {
                        $data['error'] = lang('authenication_failed') . " ({$remaining} tentativa(s) restante(s))";
                    } else {
                        $data['error'] = lang('authenication_failed');
                    }
                }
            }
        }

        $this->load->view('login/login', $data);
    }

    public function login() { $this->index(); }

    public function logout()
    {
        $this->auth->logout();
        redirect('admin/login');
    }

    // ── Tentativas de login ───────────────────────────────────
    private function _is_locked($ip, $username, $settings)
    {
        $max     = $settings->login_max_attempts ?? 5;
        $lockout = $settings->login_lockout_minutes ?? 15;
        $since   = date('Y-m-d H:i:s', strtotime("-{$lockout} minutes"));

        $count = $this->db->where('ip_address', $ip)
                          ->where('attempt_time >=', $since)
                          ->count_all_results('login_attempts');
        return $count >= $max;
    }

    private function _record_attempt($ip, $username)
    {
        $this->db->insert('login_attempts', [
            'ip_address'   => $ip,
            'username'     => $username,
            'attempt_time' => date('Y-m-d H:i:s'),
        ]);
    }

    private function _clear_attempts($ip, $username)
    {
        $this->db->where('ip_address', $ip)->delete('login_attempts');
    }

    private function _remaining_attempts($ip, $username, $settings)
    {
        $max     = $settings->login_max_attempts ?? 5;
        $lockout = $settings->login_lockout_minutes ?? 15;
        $since   = date('Y-m-d H:i:s', strtotime("-{$lockout} minutes"));
        $count   = $this->db->where('ip_address', $ip)
                            ->where('attempt_time >=', $since)
                            ->count_all_results('login_attempts');
        return max(0, $max - $count);
    }

    // ── Turnstile ─────────────────────────────────────────────
    private function _verify_turnstile($token, $secret)
    {
        if (empty($secret) || empty($token)) return true;
        $ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query(['secret' => $secret, 'response' => $token]),
            CURLOPT_TIMEOUT        => 5,
        ]);
        $resp = curl_exec($ch);
        curl_close($ch);
        if (!$resp) return true; // Se curl falhar, deixa passar
        $result = json_decode($resp, true);
        return isset($result['success']) && $result['success'] === true;
    }
}
