<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->load->library('form_validation');
    }

    /**
     * Registration page
     */
    public function register() {
        // If user is already logged in, redirect to home
        if ($this->session->userdata('user_id')) {
            redirect('home');
        }

        $data = [
            'title' => 'Register - Klimaks',
            'error' => $this->session->flashdata('error'),
            'success' => $this->session->flashdata('success')
        ];

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

    /**
     * Process registration
     */
    public function process_register() {
        // Trim password inputs before validation
        $_POST['password'] = trim($this->input->post('password'));
        $_POST['confirm_password'] = trim($this->input->post('confirm_password'));

        // Set validation rules
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[50]|is_unique[users.username]');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
        $this->form_validation->set_rules('birth_date', 'Date of Birth', 'required');
        $this->form_validation->set_rules('age_verification', 'Age Verification', 'required');

        if ($this->form_validation->run() === FALSE) {
            // Validation failed, reload registration form
            $this->register();
            return;
        }

        // Verify age is 18+
        $birth_date = $this->input->post('birth_date');
        $age = $this->calculate_age($birth_date);
        
        if ($age < 18) {
            $this->session->set_flashdata('error', 'You must be 18 years or older to register.');
            redirect('auth/register');
            return;
        }

        // Prepare user data
        $user_data = [
            'username' => $this->input->post('username'),
            'email' => $this->input->post('email'),
            'password' => $this->input->post('password'),
            'birth_date' => $birth_date,
            'is_verified' => FALSE,
            'role' => 'user'
        ];

        // Create user
        $user_id = $this->User_model->create_user($user_data);

        if ($user_id) {
            // Set success message and redirect to login
            $this->session->set_flashdata('success', 'Registration successful! Please login.');
            redirect('auth/login');
        } else {
            $this->session->set_flashdata('error', 'Registration failed. Please try again.');
            redirect('auth/register');
        }
    }

    /**
     * Login page
     */
    public function login() {
        // If user is already logged in, redirect to home
        if ($this->session->userdata('user_id')) {
            redirect('user');
        }

        $data = [
            'title' => 'Login - Klimaks',
            'error' => $this->session->flashdata('error')
        ];

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

    /**
     * Process login
     */
    public function process_login() {
        $this->form_validation->set_rules('username', 'Username or Email', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->login();
            return;
        }

        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $user = $this->User_model->verify_user($username, $password);

        if ($user) {
            if ($user->is_banned) {
                $this->session->set_flashdata('error', 'Your account has been banned.');
                redirect('auth/login');
                return;
            }

            // Set user session
            $user_data = [
                'user_id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'role' => $user->role,
                'logged_in' => TRUE
            ];
            $this->session->set_userdata($user_data);

            // Record login
            $this->User_model->record_login($user->id, $this->input->ip_address(), $this->input->user_agent());

            redirect('user');
        } else {
            $this->session->set_flashdata('error', 'Invalid username/email or password.');
            redirect('auth/login');
        }
    }

    /**
     * AJAX Login endpoint
     */
    public function ajax_login() {
        $this->output->set_content_type('application/json');
        
        $this->form_validation->set_rules('username', 'Username or Email', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');
        
        if ($this->form_validation->run() === FALSE) {
            echo json_encode([
                'success' => false,
                'errors' => $this->form_validation->error_array()
            ]);
            return;
        }
        
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        
        $user = $this->User_model->verify_user($username, $password);
        
        if ($user) {
            if ($user->is_banned) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Your account has been banned.'
                ]);
                return;
            }
            
            // Set user session
            $user_data = [
                'user_id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'role' => $user->role,
                'logged_in' => TRUE
            ];
            $this->session->set_userdata($user_data);
            
            // Record login
            $this->User_model->record_login($user->id, $this->input->ip_address(), $this->input->user_agent());
            
            echo json_encode(['success' => true]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Invalid username/email or password.'
            ]);
        }
    }
    
    /**
     * AJAX Register endpoint
     */
    public function ajax_register() {
        $this->output->set_content_type('application/json');
        
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[50]|is_unique[users.username]');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
        $this->form_validation->set_rules('birth_date', 'Date of Birth', 'required');
        $this->form_validation->set_rules('age_verification', 'Age Verification', 'required');
        
        if ($this->form_validation->run() === FALSE) {
            echo json_encode([
                'success' => false,
                'errors' => $this->form_validation->error_array()
            ]);
            return;
        }
        
        // Verify age is 18+
        $birth_date = $this->input->post('birth_date');
        $age = $this->calculate_age($birth_date);
        
        if ($age < 18) {
            echo json_encode([
                'success' => false,
                'message' => 'You must be 18 years or older to register.'
            ]);
            return;
        }
        
        // Prepare user data
        $user_data = [
            'username' => $this->input->post('username'),
            'email' => $this->input->post('email'),
            'password' => $this->input->post('password'),
            'birth_date' => $birth_date,
            'is_verified' => FALSE,
            'role' => 'user'
        ];
        
        // Create user
        $user_id = $this->User_model->create_user($user_data);
        
        if ($user_id) {
            // Auto-login after registration
            $user = $this->User_model->get_user($user_id);
            $user_data = [
                'user_id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'role' => $user->role,
                'logged_in' => TRUE
            ];
            $this->session->set_userdata($user_data);
            
            echo json_encode(['success' => true]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Registration failed. Please try again.'
            ]);
        }
    }

    /**
     * Logout
     */
    public function logout() {
        $this->session->sess_destroy();
        redirect('home');
    }

    /**
     * Calculate age from birth date
     */
    private function calculate_age($birth_date) {
        $birth = new DateTime($birth_date);
        $today = new DateTime();
        $age = $today->diff($birth)->y;
        return $age;
    }
}
