<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\StaffModel;
use App\Models\UserModel;
use App\Models\TeacherClassModel;
use App\Models\ConfigurationModel;

class StaffController extends BaseController
{
    protected $configModel;
    protected $semester;
    protected $schoolYear;
    protected $teacherClassModel;
    protected $userModel;
    protected $staffModel;

    public function __construct()
    {
        // Initialize the config model
        $this->configModel = new ConfigurationModel(); // Assuming ConfigModel is the model handling configurations
        $this->teacherClassModel = new TeacherClassModel();
        $this->userModel = new UserModel();
        $this->staffModel = new StaffModel();

        // Retrieve the configuration values
        $this->semester = $this->configModel->getConfig('semester');
        $this->schoolYear = $this->configModel->getConfig('school_year');
    }

    public function index()
    {
        // roles we never show
        $excludedRoles = ['student', 'parent', 'guest', 'inactive']; // ← add inactive here

        $staffList = $this->staffModel
            ->whereNotIn('LOWER(active_role)', array_map('strtolower', $excludedRoles))
            ->orderBy('created_at', 'DESC')
            ->findAll();

        // Preload assignments for the selected school year (across all semesters),
        // mirroring the logic used in teacher_class_assignment.
        $assignRows = $this->teacherClassModel
            ->select('teacher_class.teacher_id, teacher_class.position, classSection.class_section_name')
            ->join('classSection', 'classSection.class_section_id = teacher_class.class_section_id', 'left')
            ->where('teacher_class.school_year', (string)$this->schoolYear)
            ->findAll();

        $assignByTeacher = [];
        foreach ($assignRows as $r) {
            $tid = (int)($r['teacher_id'] ?? 0);
            if ($tid <= 0) { continue; }
            $name = trim((string)($r['class_section_name'] ?? ''));
            if ($name === '') { continue; }
            $pos  = strtolower((string)($r['position'] ?? ''));
            if (!in_array($pos, ['main','ta'], true)) { continue; }
            $assignByTeacher[$tid][] = $name . ' (' . $pos . ')';
        }

        $issuesCount = 0;
        foreach ($staffList as &$staff) {
            // attach school_id
            $staff['school_id'] = $this->userModel->getSchoolIdByUserId($staff['user_id'] ?? null);

            // Verify and attach class assignments for teacher/TA roles for the selected school year
            $role = strtolower((string)($staff['active_role'] ?? ''));
            if (in_array($role, ['teacher', 'teacher_assistant'], true)) {
                $tid = (int)($staff['user_id'] ?? 0);
                $labels = $assignByTeacher[$tid] ?? [];
                if (!empty($labels)) {
                    $staff['class_section'] = implode(', ', array_unique($labels));
                    $staff['verification_issue'] = false;
                } else {
                    $staff['class_section'] = 'No class assigned';
                    $staff['verification_issue'] = true;
                    $issuesCount++;
                }
            } else {
                $staff['class_section'] = '—';
                $staff['verification_issue'] = false;
            }
        }
        unset($staff); // break reference

        return view('staff/index', [
            'staff' => $staffList,
            'issues_count' => $issuesCount,
            'semester' => $this->semester,
            'school_year' => $this->schoolYear,
        ]);
    }

    public function create()
    {
        return view('staff/create');
    }

    public function store()
    {
        $now = utc_now();
        $payload = [
            'firstname'   => $this->request->getPost('firstname'),
            'lastname'    => $this->request->getPost('lastname'),
            'email'       => $this->request->getPost('email'),
            'phone'       => $this->request->getPost('phone'),
            'role_name'   => $this->request->getPost('role_name'),
            'school_year' => $this->request->getPost('school_year') ?: $this->schoolYear,
            'status'      => $this->request->getPost('status') ?? 'Active',
            'created_at'  => $now,
            'updated_at'  => $now,
        ];

        if (!$this->staffModel->insert($payload)) {
            return redirect()->back()->withInput()->with('error', 'Failed to create staff.');
        }

        return redirect()->to('/staff')->with('success', 'Staff member added.');
    }

    public function edit($id)
    {
        $user = $this->staffModel->find($id);

        if (!$user) {
            return redirect()->to('staff')->with('error', 'Staff member not found.');
        }

        return view('staff/edit', ['user' => $user]);
    }

    public function update($id)
    {
        // Only update fields provided by the form to avoid wiping data
        $data = [];
        foreach (['firstname','lastname','email','phone','role_name','school_year','status'] as $field) {
            $val = $this->request->getPost($field);
            if ($val !== null && $val !== '') {
                $data[$field] = $val;
            }
        }
        // Always bump updated_at
        $data['updated_at'] = utc_now();

        if (empty($data)) {
            return redirect()->back()->with('error', 'No changes detected.');
        }

        if (!$this->staffModel->update($id, $data)) {
            return redirect()->back()->withInput()->with('error', 'Failed to update staff.');
        }

        return redirect()->to('/staff')->with('success', 'Staff member updated.');
    }
}
