<?php
namespace App\Controllers;

use App\Models\MateriModel;
use App\Models\SubjectModel;

class Materi extends BaseController
{
    protected $materiModel;
    protected $subjectModel;

    public function __construct()
    {
        $this->materiModel = new MateriModel();
        $this->subjectModel = new SubjectModel();
    }

    public function index()
    {
        return view('materi/materi_index', [
            'materi' => $this->materiModel->getMateriList(),
            'mapel' => $this->subjectModel
                ->where('is_active', 1)
                ->findAll()
        ]);
    }

    public function store()
    {
        $tipe = $this->request->getPost('tipe');
        $file = $this->request->getFile('file');

        $rules = [
            'subject_id' => 'required|is_not_unique[master_subject.id]',
            'kelas' => 'required',
            'judul' => 'required|min_length[5]',
            'tipe' => 'required|in_list[PDF,VIDEO,LINK]',
        ];

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

        $path = null;

        // ================= FILE HANDLING =================
        if ($tipe !== 'LINK') {

            if (!$file || !$file->isValid()) {
                return redirect()->back()->withInput()
                    ->with('error', 'File wajib diupload');
            }

            $mimeAllowed = $tipe === 'PDF'
                ? ['application/pdf']
                : ['video/mp4', 'video/mpeg'];

            if (!in_array($file->getMimeType(), $mimeAllowed)) {
                return redirect()->back()->withInput()
                    ->with('error', 'Format file tidak sesuai');
            }

            if ($file->getSize() > 50 * 1024 * 1024) {
                return redirect()->back()->withInput()
                    ->with('error', 'Ukuran file maksimal 50MB');
            }

            $folder = $tipe === 'PDF' ? 'pdf' : 'video';
            $uploadPath = "uploads/elearning/$folder";

            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0777, true);
            }

            $newName = time() . '_' . $file->getRandomName();
            $file->move($uploadPath, $newName);

            $path = "$uploadPath/$newName";
        }

        // ================= SAVE DB =================
        $this->materiModel->insert([
            'subject_id' => $this->request->getPost('subject_id'),
            'kelas' => $this->request->getPost('kelas'),
            'judul' => $this->request->getPost('judul'),
            'deskripsi' => $this->request->getPost('deskripsi'),
            'tipe' => $tipe,
            'file_path' => $path,
            'created_by' => session('user_id'),
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return redirect()->to('elearning/materi')
            ->with('success', 'Materi berhasil diupload');
    }
    public function filter()
    {
        $materiModel = new \App\Models\MateriModel();

        $keyword = $this->request->getGet('keyword');
        $mapel = $this->request->getGet('mapel');
        $kelas = $this->request->getGet('kelas');

        $builder = $materiModel
            ->select('materi.*, master_subject.nama_mapel')
            ->join('master_subject', 'master_subject.id = materi.subject_id', 'left');

        if ($keyword) {
            $builder->like('materi.judul', $keyword);
        }

        if ($mapel) {
            $builder->where('materi.subject_id', $mapel);
        }

        if ($kelas) {
            $builder->where('materi.kelas', $kelas);
        }

        $data['materi'] = $builder->orderBy('materi.created_at', 'DESC')->findAll();

        return view('materi/_materi_cards', $data);
    }

}
