<?php
class Auth extends CI_Controller {

	public function __construct() {
		parent::__construct();
		// Load the necessary models and helpers
		$this->load->model('User_model');
		$this->load->helper('url');

		// Load the session library
		$this->load->library('session');
	}

	// Show the login page
	public function login() {
		$this->load->view('auth/login');
	}

	// Show the signup page
	public function signup() {
		$this->load->view('auth/signup');
	}

	// Process the login
	public function login_process() {
		$username = $this->input->post('username');
		$password = $this->input->post('password');

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

		if ($user) {
			// Set session data
			$this->session->set_userdata('user_id', $user->id);
			$this->session->set_userdata('username', $user->username);
			redirect('tasks'); // Redirect to tasks page
		} else {
			$this->session->set_flashdata('error', 'Invalid username or password');
			redirect('auth/login');
		}
	}

	// Process the signup
	public function signup_process() {
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$email = $this->input->post('email');

		// Check if username or email already exists
		if ($this->User_model->username_exists($username)) {
			$this->session->set_flashdata('error', 'Username already exists');
			redirect('auth/signup');
		}

		if ($this->User_model->email_exists($email)) {
			$this->session->set_flashdata('error', 'Email already exists');
			redirect('auth/signup');
		}

		// Prepare data for registration
		$data = [
			'username' => $username,
			'password' => $password,
			'email' => $email
		];

		// Register user
		if ($this->User_model->register_user($data)) {
			$this->session->set_flashdata('success', 'Registration successful. Please log in.');
			redirect('auth/login');
		} else {
			$this->session->set_flashdata('error', 'Registration failed. Please try again.');
			redirect('auth/signup');
		}
	}

	// Log the user out
	public function logout() {
		$this->session->unset_userdata(['user_id', 'username']);
		redirect('auth/login');
	}
}
?>
