<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;
use App\Models\Department;
use App\Models\Module;
use App\Http\Controllers\Siswa\BaseController;

class DashboardController extends BaseController
{
    /**
     * Convert array → stdClass (deep)
     */
    private function toObject($data)
    {
        return json_decode(json_encode($data));
    }

    public function index()
    {
        $response = Http::withToken(session('token'))
            ->get(config('services.lms.api') . '/siswa/dashboard');

        // 🔐 Token expired
        if ($redirect = $this->handleApi($response)) {
            return $redirect;
        }
        
        if ($response->failed()) {
            return redirect()
                ->route('siswa.dashboard')
                ->with('error','Gagal mengambil data dashboard');
        }

        $data = $response->json('data');

        /* ===============================
         * OBJECT UTAMA (SAMA FE LAMA)
         * =============================== */
        $user    = $this->toObject($data['user']);
        $student = $this->toObject($data['student']);

        /* ===============================
         * DEPARTMENTS
         * =============================== */
        $departments = collect($data['departments'])
            ->filter(fn ($d) => ($d['is_global'] ?? 0) != 1)
            ->map(fn ($d) => $this->toObject($d));

        /* ===============================
         * MODULES + LESSONS (KRUSIAL)
         * =============================== */
$myModules = collect($data['myModules'])->map(function ($m) {

    $m = $this->toObject($m);

    // ===============================
    // LESSONS (SUDAH ADA)
    // ===============================
    if (isset($m->lessons) && is_array($m->lessons)) {
        $m->lessons = collect($m->lessons)
            ->map(fn ($l) => (object) $l);
    } else {
        $m->lessons = collect();
    }

    // ===============================
    // 🔥 TAMBAHAN BARU - SCHEDULES
    // ===============================
    if (isset($m->schedules) && is_array($m->schedules)) {
        $m->schedules = collect($m->schedules)
            ->map(fn ($s) => (object) $s);
    } else {
        $m->schedules = collect();
    }

    return $m;
});

        /* ===============================
         * QUIZ & TASK - DENGAN FORMAT DEADLINE
         * =============================== */
        $upcomingQuizzes = collect($data['upcomingQuizzes'])
            ->map(function ($q) {
                $q = (object) $q;
                
                // Gunakan format dari BE jika ada, atau format sendiri
                if (!empty($q->deadline_formatted)) {
                    $q->deadline_formatted = $q->deadline_formatted;
                } elseif (!empty($q->deadline)) {
                    try {
                        $q->deadline_formatted = Carbon::parse($q->deadline)
                            ->translatedFormat('d F Y H:i');
                    } catch (\Exception $e) {
                        $q->deadline_formatted = 'Tanpa batas waktu';
                    }
                } else {
                    $q->deadline_formatted = 'Tanpa batas waktu';
                }
                
                return $q;
            });

        $upcomingTasks = collect($data['upcomingTasks'])
            ->map(function ($t) {
                $t = (object) $t;
                
                // Gunakan format dari BE jika ada, atau format sendiri
                if (!empty($t->deadline_formatted)) {
                    $t->deadline_formatted = $t->deadline_formatted;
                } elseif (!empty($t->deadline)) {
                    try {
                        $t->deadline_formatted = Carbon::parse($t->deadline)
                            ->translatedFormat('d F Y H:i');
                    } catch (\Exception $e) {
                        $t->deadline_formatted = 'Tanpa batas waktu';
                    }
                } else {
                    $t->deadline_formatted = 'Tanpa batas waktu';
                }
                
                return $t;
            });

        return view('siswa.dashboard', compact(
            'user',
            'student',
            'departments',
            'myModules',
            'upcomingQuizzes',
            'upcomingTasks'
        ));
    }
}