<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AiKbCpModel;
use App\Models\SubjectModel;
use App\Models\AcademicYearModel;

class CpManagement extends BaseController
{
    protected $cpModel;
    protected $subjectModel;
    protected $academicYearModel;
    protected $teachingAssignmentModel;
    protected $teacherModel;
    protected $periodModel;

    public function __construct()
    {
        $this->cpModel = new AiKbCpModel();
        $this->subjectModel = new SubjectModel();
        $this->academicYearModel = new AcademicYearModel();
        
        $this->teachingAssignmentModel = new \App\Models\TeachingAssignmentModel();
        $this->teacherModel = new \App\Models\TeacherModel();
        $this->periodModel = new \App\Models\AcademicPeriodModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin', 'guru'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }
        return null;
    }

    private function getTeacherAssignedSubjects()
    {
        if (session()->get('user_role') !== 'guru') {
            return null; // Admin sees all
        }

        $teacher = $this->teacherModel->where('user_id', session()->get('user_id'))->first();
        if (!$teacher) return [];

        $activePeriod = $this->periodModel->getActive();
        if (!$activePeriod) return [];

        // Get assigned subjects mapping to master subject_id or names
        $assigned = $this->teachingAssignmentModel
            ->select('school_subjects.subject_id as master_subject_id, school_subjects.name as subject_name')
            ->join('school_subjects', 'school_subjects.id = teaching_assignments.subject_id')
            ->where('teaching_assignments.teacher_id', $teacher['id'])
            ->where('teaching_assignments.academic_period_id', $activePeriod['id'])
            ->groupBy('school_subjects.subject_id, school_subjects.name')
            ->findAll();

        return $assigned;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $cps = $this->cpModel->getDetailedList();
        $assignedSubjects = $this->getTeacherAssignedSubjects();

        if ($assignedSubjects !== null) {
            $filteredCps = [];
            foreach ($cps as $cp) {
                $isMatch = false;
                foreach ($assignedSubjects as $as) {
                    if (($cp['subject_id'] && $cp['subject_id'] == $as['master_subject_id']) || 
                        strcasecmp($cp['subject_name'], $as['subject_name']) == 0) {
                        $isMatch = true;
                        break;
                    }
                }
                if ($isMatch) {
                    $filteredCps[] = $cp;
                }
            }
            $cps = $filteredCps;
        }

        $data = [
            'title' => 'Master Capaian Pembelajaran (CP) Lokal',
            'cps'   => $cps,
        ];

        return view('admin/cp_management/index', $data);
    }

    public function create()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $subjects = $this->subjectModel->orderBy('name', 'ASC')->findAll();
        $assignedSubjects = $this->getTeacherAssignedSubjects();

        if ($assignedSubjects !== null) {
            $filteredSubjects = [];
            foreach ($subjects as $s) {
                foreach ($assignedSubjects as $as) {
                    if ($s['id'] == $as['master_subject_id'] || strcasecmp($s['name'], $as['subject_name']) == 0) {
                        $filteredSubjects[] = $s;
                        break;
                    }
                }
            }
            $subjects = $filteredSubjects;
        }

        $data = [
            'title'          => 'Tambah Capaian Pembelajaran',
            'subjects'       => $subjects,
            'academic_years' => $this->academicYearModel->orderBy('start_date', 'DESC')->findAll(),
        ];

        return view('admin/cp_management/form', $data);
    }

    public function store()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'phase'            => 'required|in_list[A,B,C,D,E,F]',
            'subject_name'     => 'required|max_length[100]',
            'academic_year_id' => 'required|numeric'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $subjectId = $this->request->getPost('subject_id');
        $subjectName = $this->request->getPost('subject_name');

        if (!empty($subjectId)) {
            $subject = $this->subjectModel->find($subjectId);
            if ($subject) {
                $subjectName = $subject['name'];
            }
        } else {
            $subjectId = null;
        }

        $elementsInput = $this->request->getPost('elements');
        $elements = null;
        if (is_array($elementsInput) && !empty($elementsInput['name'])) {
            $parsedElements = [];
            foreach ($elementsInput['name'] as $idx => $name) {
                if (!empty(trim($name))) {
                    $parsedElements[] = [
                        'name' => trim($name),
                        'description' => trim($elementsInput['description'][$idx] ?? '')
                    ];
                }
            }
            if (!empty($parsedElements)) {
                $elements = json_encode($parsedElements);
            }
        }

        if (empty($elements)) {
            return redirect()->back()
                ->with('error', 'Minimal harus ada 1 Elemen CP dan Deskripsinya.')
                ->withInput();
        }

        $this->cpModel->insert([
            'academic_year_id' => $this->request->getPost('academic_year_id'),
            'user_id'          => session()->get('user_id'),
            'subject_id'       => $subjectId,
            'subject_name'     => $subjectName,
            'phase'            => $this->request->getPost('phase'),
            'content'          => ' ', // Discarded content
            'elements'         => $elements,
        ]);

        return redirect()->to('/cp-management')
            ->with('success', 'Master Capaian Pembelajaran (CP) berhasil ditambahkan!');
    }

    public function edit($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $cp = $this->cpModel->find($id);
        if (!$cp) {
            return redirect()->to('/cp-management')->with('error', 'Data CP tidak ditemukan!');
        }

        if (session()->get('user_role') === 'guru' && $cp['user_id'] != session()->get('user_id')) {
            return redirect()->to('/cp-management')->with('error', 'Anda tidak memiliki hak untuk mengedit CP ini!');
        }

        $subjects = $this->subjectModel->orderBy('name', 'ASC')->findAll();
        $assignedSubjects = $this->getTeacherAssignedSubjects();

        if ($assignedSubjects !== null) {
            $filteredSubjects = [];
            foreach ($subjects as $s) {
                foreach ($assignedSubjects as $as) {
                    if ($s['id'] == $as['master_subject_id'] || strcasecmp($s['name'], $as['subject_name']) == 0) {
                        $filteredSubjects[] = $s;
                        break;
                    }
                }
            }
            $subjects = $filteredSubjects;
        }

        $data = [
            'title'          => 'Edit Capaian Pembelajaran',
            'cp'             => $cp,
            'subjects'       => $subjects,
            'academic_years' => $this->academicYearModel->orderBy('start_date', 'DESC')->findAll(),
        ];

        return view('admin/cp_management/form', $data);
    }

    public function update($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $cp = $this->cpModel->find($id);
        if (!$cp) {
            return redirect()->to('/cp-management')->with('error', 'Data CP tidak ditemukan!');
        }

        if (session()->get('user_role') === 'guru' && $cp['user_id'] != session()->get('user_id')) {
            return redirect()->to('/cp-management')->with('error', 'Anda tidak memiliki hak untuk mengupdate CP ini!');
        }

        $rules = [
            'phase'            => 'required|in_list[A,B,C,D,E,F]',
            'subject_name'     => 'required|max_length[100]',
            'academic_year_id' => 'required|numeric'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $subjectId = $this->request->getPost('subject_id');
        $subjectName = $this->request->getPost('subject_name');

        if (!empty($subjectId)) {
            $subject = $this->subjectModel->find($subjectId);
            if ($subject) {
                $subjectName = $subject['name'];
            }
        } else {
            $subjectId = null;
        }

        $elementsInput = $this->request->getPost('elements');
        $elements = null;
        if (is_array($elementsInput) && !empty($elementsInput['name'])) {
            $parsedElements = [];
            foreach ($elementsInput['name'] as $idx => $name) {
                if (!empty(trim($name))) {
                    $parsedElements[] = [
                        'name' => trim($name),
                        'description' => trim($elementsInput['description'][$idx] ?? '')
                    ];
                }
            }
            if (!empty($parsedElements)) {
                $elements = json_encode($parsedElements);
            }
        }

        if (empty($elements)) {
            return redirect()->back()
                ->with('error', 'Minimal harus ada 1 Elemen CP dan Deskripsinya.')
                ->withInput();
        }

        $this->cpModel->update($id, [
            'academic_year_id' => $this->request->getPost('academic_year_id'),
            'subject_id'       => $subjectId,
            'subject_name'     => $subjectName,
            'phase'            => $this->request->getPost('phase'),
            'content'          => ' ', // Discarded content
            'elements'         => $elements,
        ]);

        return redirect()->to('/cp-management')
            ->with('success', 'Master Capaian Pembelajaran (CP) berhasil diperbarui!');
    }

    public function delete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $cp = $this->cpModel->find($id);
        if (!$cp) {
            return redirect()->to('/cp-management')->with('error', 'Data CP tidak ditemukan!');
        }

        if (session()->get('user_role') === 'guru' && $cp['user_id'] != session()->get('user_id')) {
            return redirect()->to('/cp-management')->with('error', 'Anda tidak memiliki hak untuk menghapus CP ini!');
        }

        $this->cpModel->delete($id);

        return redirect()->to('/cp-management')
            ->with('success', 'Master Capaian Pembelajaran (CP) berhasil dihapus!');
    }
}
