<?php

namespace App\Controllers\Elearning;

use App\Controllers\BaseController;
use App\Repositories\Elearning\TaskRepository;

class Task extends BaseController
{
    protected TaskRepository $repo;

    public function __construct()
    {
        $this->repo = new TaskRepository();
    }

    // =========================
    // LIST TUGAS SISWA
    // =========================
    public function index()
    {
        $userId = session()->get('id');

        if (!$userId) {
            return redirect()->to(site_url('login'));
        }

        $tasks = $this->repo->getTasksByUser((int) $userId);

        foreach ($tasks as &$task) {
            $task = $this->repo->enrichTaskStatus($task);
        }

        return view('elearning/task/index', compact('tasks'));
    }

    // =========================
    // DETAIL TUGAS
    // =========================
    public function view(int $id)
    {
        $userId = session()->get('id');

        if (!$userId) {
            return redirect()->to(site_url('login'));
        }

        $task = $this->repo->getTaskDetail($id);
        if (!$task) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException();
        }

        $submission = $this->repo->getSubmission($id, $userId);
        $task = $this->repo->enrichTaskStatus($task, $submission);

        return view('elearning/task/view', compact('task'));
    }

    // =========================
    // SUBMIT JAWABAN SISWA
    // =========================
    public function submit(int $taskId)
    {
        $userId = session()->get('id');

        if (!$userId) {
            return redirect()->to(site_url('login'));
        }

        $task = $this->repo->getTaskDetail($taskId);
        if (!$task) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException();
        }

        // ⛔ Cegah submit setelah deadline
        if (time() > strtotime($task['deadline'])) {
            return redirect()->back()->with('error', 'Deadline telah berakhir');
        }

        $file = $this->request->getFile('file_jawaban');
        if (!$file || !$file->isValid()) {
            return redirect()->back()->with('error', 'File tidak valid');
        }

        $newName = $file->getRandomName();
        $file->move(FCPATH . 'uploads/jawaban', $newName);

        // 💾 SIMPAN / UPDATE SUBMISSION
        $this->repo->saveJawaban([
            'task_id'    => $taskId,
            'user_id'    => $userId,
            'file'       => $newName,
            'status'     => 'submitted', // 🔥 STATUS DIUBAH
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        return redirect()
            ->to(site_url('elearning/task/view/' . $taskId))
            ->with('success', 'Jawaban berhasil dikirim');
    }
}
