<?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', 'Security_lib']);
        $this->load->helper(['admission', 'url']);
    }
    
    public function index() {
        redirect('auth/login');
    }
    
    public function login() {
        if (is_logged_in()) {
            redirect('dashboard');
        }
        
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
        
        if ($this->form_validation->run() === TRUE) {
            $email = sanitize_input($this->input->post('email'));
            $password = $this->input->post('password');
            
            // Check login attempts
            if (!$this->security_lib->check_login_attempts($email)) {
                $this->session->set_flashdata('error', 'Account locked. Try again in 15 minutes.');
                redirect('login');
            }
            
            $user = $this->User_model->authenticate($email, $password);
            
            if ($user) {
                // Record successful login
                $this->security_lib->record_login_attempt($email, true);
                $this->security_lib->audit_log('login_success', ['email' => $email]);
                
                // Set session
                $session_data = [
                    'user_id' => $user->id,
                    'email' => $user->email,
                    'role' => $user->role,
                    'logged_in' => TRUE,
                    'csrf_token' => $this->security_lib->generate_csrf_token()
                ];
                $this->session->set_userdata($session_data);
                
                // Redirect based on role
                redirect('dashboard');
            } else {
                // Record failed attempt
                $this->security_lib->record_login_attempt($email, false);
                $this->security_lib->audit_log('login_failed', ['email' => $email]);
                
                $this->session->set_flashdata('error', 'Invalid email or password');
                redirect('login');
            }
        }
        
        $data['title'] = 'Login - Admission System';
        $this->load->view('auth/login', $data);
    }
    
    public function signup() {
        if (is_logged_in()) {
            redirect('dashboard');
        }
        
        $this->form_validation->set_rules('email', 'Email', 
            'required|valid_email|is_unique[users.email]|trim',
            ['is_unique' => 'This email is already registered']
        );
        $this->form_validation->set_rules('password', 'Password', 
            'required|min_length[8]|regex_match[/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/]',
            ['regex_match' => 'Password must contain uppercase, lowercase, and number']
        );
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 
            'required|matches[password]'
        );
        $this->form_validation->set_rules('terms', 'Terms & Conditions', 
            'required', 
            ['required' => 'You must accept the terms and conditions']
        );
        
        if ($this->form_validation->run() === TRUE) {
            $user_data = [
                'email' => sanitize_input($this->input->post('email')),
                'password' => $this->input->post('password'),
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            $user_id = $this->User_model->create_user($user_data);
            
            if ($user_id) {
                $this->security_lib->audit_log('signup', ['email' => $user_data['email']]);
                
                // Auto login after signup
                $user = $this->User_model->authenticate($user_data['email'], $user_data['password']);
                $session_data = [
                    'user_id' => $user->id,
                    'email' => $user->email,
                    'role' => $user->role,
                    'logged_in' => TRUE,
                    'csrf_token' => $this->security_lib->generate_csrf_token()
                ];
                $this->session->set_userdata($session_data);
                
                $this->session->set_flashdata('success', 'Account created successfully! Please complete your profile.');
                redirect('profile/bio-data');
            } else {
                $this->session->set_flashdata('error', 'Failed to create account. Please try again.');
            }
        }
        
        $data['title'] = 'Sign Up - Admission System';
        $this->load->view('auth/signup', $data);
    }
    
    public function forgot_password() {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        
        if ($this->form_validation->run() === TRUE) {
            $email = sanitize_input($this->input->post('email'));
            $user = $this->User_model->get_by_email($email);
            
            if ($user) {
                // Generate reset token
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                // Save token to database (you need to create password_resets table)
                $this->db->insert('password_resets', [
                    'email' => $email,
                    'token' => $token,
                    'expires_at' => $expires
                ]);
                
                // Send email (implement email sending)
                $this->security_lib->audit_log('password_reset_request', ['email' => $email]);
                
                $this->session->set_flashdata('success', 'Password reset link sent to your email.');
            } else {
                $this->session->set_flashdata('error', 'Email not found.');
            }
        }
        
        $data['title'] = 'Forgot Password';
        $this->load->view('auth/forgot_password', $data);
    }
    
    public function logout() {
        $this->security_lib->audit_log('logout', ['user_id' => $this->session->userdata('user_id')]);
        $this->session->sess_destroy();
        redirect('login');
    }
}