<?php

namespace App\Repositories\Elearning;

use App\Models\Elearning\TaskModel;
use CodeIgniter\Database\BaseConnection;
use Config\Database;

class TaskRepository
{
    protected TaskModel $task;
    protected BaseConnection $db;

    public function __construct()
    {
        $this->task = new TaskModel();
        $this->db = Database::connect();
    }

    /* ===============================
       LIST TUGAS SISWA
    =============================== */
    public function getTasksByUser(int $userId): array
    {
        return $this->db->table('elearning_tasks t')
            ->select([
                't.id',
                't.judul',
                't.kelas',
                't.guru',
                't.deadline',
                't.deskripsi',
                'm.nama_mapel AS mapel',
                's.id AS submission_id',
                's.created_at AS submitted_at'
            ])
            ->join('mapel m', 'm.id = t.mapel_id', 'left')
            ->join(
                'elearning_task_submissions s',
                's.task_id = t.id AND s.user_id = ' . (int) $userId,
                'left'
            )
            ->orderBy('t.deadline', 'ASC')
            ->get()
            ->getResultArray();
    }

    /* ===============================
       DETAIL TUGAS
    =============================== */
    public function getTaskDetail(int $taskId): ?array
    {
        return $this->db->table('elearning_tasks t')
            ->select('t.*, m.nama_mapel AS mapel')
            ->join('mapel m', 'm.id = t.mapel_id', 'left')
            ->where('t.id', $taskId)
            ->get()
            ->getRowArray();
    }

    public function getSubmission(int $taskId, int $userId): ?array
    {
        return $this->db->table('elearning_task_submissions')
            ->where([
                'task_id' => $taskId,
                'user_id' => $userId
            ])
            ->get()
            ->getRowArray();
    }

    public function saveJawaban(array $data): bool
    {
        return $this->db
            ->table('elearning_task_submissions')
            ->insert($data);
    }

    public function enrichTaskStatus(array $task, ?array $submission = null): array
    {
        if ($submission) {
            $task['status'] =
                strtotime($submission['created_at']) <= strtotime($task['deadline'])
                ? 'Sudah' : 'Telat';
        } else {
            $task['status'] =
                time() > strtotime($task['deadline'])
                ? 'Telat' : 'Belum';
        }

        $task['badge'] = match ($task['status']) {
            'Sudah' => 'success',
            'Telat' => 'danger',
            default => 'warning'
        };

        $task['is_active'] = $task['status'] === 'Belum';

        return $task;
    }

}
