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

class User_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    /**
     * Authenticate a user by username and password
     *
     * @param string $username
     * @param string $password
     * @return object|bool Returns the user object on success, FALSE on failure
     */
    public function authenticate($username, $password) {
        $this->db->select('users.*, roles.name as role');
        $this->db->from('users');
        $this->db->join('roles', 'roles.id = users.role_id');
        $this->db->where('username', $username);
        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            $user = $query->row();
            
            if (password_verify($password, $user->password)) {
                return $user;
            }
        }
        
        return false;
    }

    /**
     * Register a new student
     *
     * @param array $data
     * @return bool
     */
    public function register_student($data) {
        // Get the student role_id
        $this->db->where('name', 'student');
        $role_query = $this->db->get('roles');
        if ($role_query->num_rows() == 0) {
            return false;
        }
        $role_id = $role_query->row()->id;

        // Check if username already exists
        $this->db->where('username', $data['username']);
        $query = $this->db->get('users');
        if ($query->num_rows() > 0) {
            return false;
        }

        // Check if phone already exists
        $this->db->where('phone', $data['phone']);
        $query = $this->db->get('users');
        if ($query->num_rows() > 0) {
            return false;
        }
        
        // Check if email already exists
        $this->db->where('email', $data['email']);
        $query = $this->db->get('users');
        if ($query->num_rows() > 0) {
            return false;
        }

        $insert_data = [
            'full_name' => $data['full_name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
            'phone' => $data['phone'],
            'class_level' => $data['class_level'],
            'gender' => $data['gender'],
            'role_id' => $role_id
        ];

        return $this->db->insert('users', $insert_data);
    }
}
