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

class Admin_model extends CI_Model {

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

    /**
     * Ensures that the complex backend relationships (departments, programs, years, classes)
     * exist so the admin can easily just assign things to "Form 1", "Form 2", etc.
     */
    private function auto_seed_school_structure() {
        // Check if academic year exists, if not create default
        $this->db->where('name', '2025-2026');
        $query = $this->db->get('academic_years');
        if ($query->num_rows() == 0) {
            $this->db->insert('academic_years', ['name' => '2025-2026']);
            $year_id = $this->db->insert_id();
            
            // Create default terms (Term 1, 2, 3)
            $this->db->insert('semesters', ['academic_year_id' => $year_id, 'name' => 'Term 1']);
            $term1_id = $this->db->insert_id();
            $this->db->insert('semesters', ['academic_year_id' => $year_id, 'name' => 'Term 2']);
            $this->db->insert('semesters', ['academic_year_id' => $year_id, 'name' => 'Term 3']);
            
            // Create default department
            $this->db->insert('departments', ['name' => 'Secondary Education', 'description' => 'Main school department']);
            $dept_id = $this->db->insert_id();
            
            // Create default program
            $this->db->insert('programs', ['department_id' => $dept_id, 'name' => 'General Secondary', 'description' => 'Standard curriculum']);
            $prog_id = $this->db->insert_id();
            
            // Create Forms 1-4 for Term 1
            $forms = ['Form 1', 'Form 2', 'Form 3', 'Form 4'];
            foreach ($forms as $form) {
                $this->db->insert('classes', [
                    'program_id' => $prog_id,
                    'name' => $form,
                    'section' => 'A',
                    'academic_year_id' => $year_id,
                    'semester_id' => $term1_id
                ]);
            }
        }
    }

    // --- SUBJECTS ---
    
    public function get_subjects() {
        return $this->db->get('subjects')->result();
    }

    public function add_subject($data) {
        // Prevent duplicate codes
        $this->db->where('code', $data['code']);
        if ($this->db->get('subjects')->num_rows() > 0) {
            return false;
        }
        return $this->db->insert('subjects', $data);
    }

    // --- CLASSES ---

    public function get_classes() {
        return $this->db->get('classes')->result();
    }

    // --- TEACHERS ---

    public function get_teachers() {
        // Find teacher role_id
        $this->db->where('name', 'teacher');
        $role = $this->db->get('roles')->row();
        
        if (!$role) return [];
        
        $this->db->where('role_id', $role->id);
        return $this->db->get('users')->result();
    }

    // --- ASSIGNMENTS ---

    public function assign_teacher_to_class($teacher_id, $subject_id, $class_id) {
        // Check if assignment already exists
        $this->db->where([
            'teacher_id' => $teacher_id,
            'subject_id' => $subject_id,
            'class_id' => $class_id
        ]);
        if ($this->db->get('teacher_subjects')->num_rows() > 0) {
            return false; // Already assigned
        }
        
        return $this->db->insert('teacher_subjects', [
            'teacher_id' => $teacher_id,
            'subject_id' => $subject_id,
            'class_id' => $class_id
        ]);
    }
    
    public function get_assignments() {
        $this->db->select('ts.teacher_id, ts.subject_id, ts.class_id, u.full_name as teacher_name, s.name as subject_name, c.name as class_name');
        $this->db->from('teacher_subjects ts');
        $this->db->join('users u', 'u.id = ts.teacher_id');
        $this->db->join('subjects s', 's.id = ts.subject_id');
        $this->db->join('classes c', 'c.id = ts.class_id');
        return $this->db->get()->result();
    }

    // --- STATISTICS ---

    public function get_total_students() {
        $this->db->join('roles', 'roles.id = users.role_id');
        $this->db->where('roles.name', 'student');
        return $this->db->count_all_results('users');
    }

    public function get_total_teachers() {
        $this->db->join('roles', 'roles.id = users.role_id');
        $this->db->where('roles.name', 'teacher');
        return $this->db->count_all_results('users');
    }

    public function get_total_subjects() {
        return $this->db->count_all('subjects');
    }

    public function get_total_classes() {
        return $this->db->count_all('classes');
    }

    // --- TEACHERS MANAGEMENT ---



    public function insert_teacher($data) {
        // Prevent duplicate usernames
        $this->db->where('username', $data['username']);
        if ($this->db->get('users')->num_rows() > 0) {
            return false;
        }

        $this->db->where('name', 'teacher');
        $role = $this->db->get('roles')->row();
        if (!$role) 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'],
            'role_id' => $role->id,
            'role' => 'teacher' // fallback for older code if any
        ];
        
        return $this->db->insert('users', $insert_data);
    }
}
