<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SchoolSubjectModel;
use App\Models\SubjectModel;
use App\Models\SchoolSettingModel;

class SchoolSubject extends BaseController
{
    protected $schoolSubjectModel;
    protected $subjectModel;
    protected $settingModel;

    public function __construct()
    {
        $this->schoolSubjectModel = new SchoolSubjectModel();
        $this->subjectModel       = new SubjectModel();
        $this->settingModel       = new SchoolSettingModel();
    }

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

    private function getSchoolLevel()
    {
        $setting = $this->settingModel->first();
        $schoolType = $setting['school_type'] ?? 'MTs';
        
        $levelMap = [
            'TK'  => 'TK',
            'SD'  => 'SD',
            'SMP' => 'SMP',
            'SMA' => 'SMA',
            'SMK' => 'SMK',
            'RA' => 'MI',
            'MI' => 'MI',
            'MTs' => 'MTs',
            'MA' => 'MA',
            'MAK' => 'MA',
        ];
        
        return $levelMap[$schoolType] ?? 'ALL';
    }

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

        $schoolLevel = $this->getSchoolLevel();
        
        // Ambil mapel yang sudah aktif di sekolah
        $subjects = $this->schoolSubjectModel->getActiveSubjects();
        
        // Jika belum ada, tampilkan array kosong
        if ($subjects === null) {
            $subjects = [];
        }
        
        $data = [
            'title'            => 'Setting Mapel Sekolah',
            'school_level'     => $schoolLevel,
            'subjects'         => $subjects,  // ← PASTIKAN INI ADA
            'master_subjects'  => [], // opsional, untuk modal
            'active_ids'       => [],
        ];

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

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

        $level = $this->getSchoolLevel();
        $masterSubjects = $this->subjectModel->getByLevel($level);
        
        // Tandai mana yang sudah ada di school_subjects
        $existingSubjects = $this->schoolSubjectModel
                                ->select('subject_id, is_active')
                                ->where('subject_id IS NOT NULL')
                                ->findAll();
        $existingMap = [];
        foreach ($existingSubjects as $ex) {
            $existingMap[$ex['subject_id']] = $ex['is_active'];
        }
        
        $result = [];
        foreach ($masterSubjects as $subject) {
            $result[] = [
                'id' => $subject['id'],
                'name' => $subject['name'],
                'code' => $subject['code'],
                'group' => $subject['group'],
                'phase' => $subject['phase'],
                'is_already_added' => isset($existingMap[$subject['id']]),
                'is_active' => $existingMap[$subject['id']] ?? false,
            ];
        }
        
        return $this->response->setJSON($result);
    }

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

        $selectedIds = $this->request->getPost('subject_ids') ?? [];
        
        // Hapus semua yang tidak dipilih
        $this->schoolSubjectModel->where('subject_id IS NOT NULL')->delete();
        
        // Simpan yang dipilih
        $success = 0;
        foreach ($selectedIds as $subjectId) {
            $master = $this->subjectModel->find($subjectId);
            if ($master) {
                $this->schoolSubjectModel->insert([
                    'subject_id' => $subjectId,
                    'name'       => $master['name'],
                    'code'       => $master['code'],
                    'is_active'  => 1,
                ]);
                $success++;
            }
        }
        
        return redirect()->to('/school-subject')
            ->with('success', "Berhasil menyimpan {$success} mapel untuk sekolah.");
    }

    // Proses ambil dari master (simpan yang dicentang)
    public function importFromMaster()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $selectedIds = $this->request->getPost('subject_ids');
        
        if (empty($selectedIds)) {
            return redirect()->back()->with('error', 'Pilih mata pelajaran terlebih dahulu!');
        }
        
        $success = 0;
        $skipped = 0;
        
        foreach ($selectedIds as $subjectId) {
            // Cek apakah sudah ada
            if ($this->schoolSubjectModel->exists($subjectId)) {
                $skipped++;
                continue;
            }
            
            $master = $this->subjectModel->find($subjectId);
            if ($master) {
                $this->schoolSubjectModel->insert([
                    'subject_id' => $subjectId,
                    'name'       => $master['name'],
                    'code'       => $master['code'],
                    'is_active'  => 1,
                ]);
                $success++;
            }
        }
        
        return redirect()->to('/school-subject')
            ->with('success', "Berhasil menambahkan {$success} mapel. {$skipped} mapel sudah ada.");
    }

    // Tambah manual (mapel lokal)
    public function store()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'name' => 'required|max_length[100]',
        ];

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

        // Cek duplikasi nama
        if ($this->schoolSubjectModel->exists(null, $this->request->getPost('name'))) {
            return redirect()->back()
                ->with('error', 'Nama mapel sudah ada!')
                ->withInput();
        }

        $this->schoolSubjectModel->insert([
            'subject_id' => null,
            'name'       => $this->request->getPost('name'),
            'code'       => $this->request->getPost('code'),
            'is_active'  => 1,
        ]);

        return redirect()->to('/school-subject')
            ->with('success', 'Mapel lokal berhasil ditambahkan!');
    }

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

        $rules = [
            'name' => 'required|max_length[100]',
        ];

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

        // Cek duplikasi nama (exclude current)
        $existing = $this->schoolSubjectModel
                         ->where('name', $this->request->getPost('name'))
                         ->where('id !=', $id)
                         ->first();
        
        if ($existing) {
            return redirect()->back()
                ->with('error', 'Nama mapel sudah ada!')
                ->withInput();
        }

        $this->schoolSubjectModel->update($id, [
            'name'      => $this->request->getPost('name'),
            'code'      => $this->request->getPost('code'),
            'is_active' => $this->request->getPost('is_active') ? 1 : 0,
        ]);

        return redirect()->to('/school-subject')
            ->with('success', 'Mapel berhasil diupdate!');
    }

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

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

        return redirect()->to('/school-subject')
            ->with('success', 'Mapel berhasil dihapus!');
    }

    // Nonaktifkan mapel (AJAX)
    public function toggleActive($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $subject = $this->schoolSubjectModel->find($id);
        if ($subject) {
            $newStatus = $subject['is_active'] ? 0 : 1;
            $this->schoolSubjectModel->update($id, ['is_active' => $newStatus]);
            return $this->response->setJSON([
                'success' => true,
                'is_active' => $newStatus
            ]);
        }
        
        return $this->response->setJSON(['success' => false]);
    }

    // Update urutan mapel (AJAX)
    public function updateOrder()
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        
        $items = $this->request->getPost('items');
        
        if (empty($items) || !is_array($items)) {
            return $this->response->setJSON([
                'success' => false, 
                'message' => 'Tidak ada data'
            ]);
        }
        
        $items = array_map('intval', $items);
        
        $db = \Config\Database::connect();
        $db->transStart();
        
        foreach ($items as $index => $id) {
            $db->table('school_subjects')
            ->where('id', $id)
            ->update(['sort_order' => $index + 1]);
        }
        
        $db->transComplete();
        
        if ($db->transStatus()) {
            return $this->response->setJSON(['success' => true]);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Gagal update database']);
        }
    }

}
