<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Siswa\BaseController;

class CourseController extends BaseController
{
    /**
     * ===============================
     * HALAMAN KURSUS SISWA (FE)
     * ===============================
     */
    public function index(Request $request)
    {
        $response = Http::withToken(session('token'))
            ->get(
                config('services.lms.api') . '/siswa/kursus',
                $request->only('q')
            );

         // 🔥 GLOBAL HANDLER (401,403,404,500)
        if ($redirect = $this->handleApi($response)) {
            return $redirect;
        }

        // ❌ Friendly error
        if ($response->failed()) {
            return redirect()
                ->route('siswa.dashboard')
                ->with('error','Gagal mengambil data kursus');
        }
        
        /**
         * ⚠️ NAMA & STRUKTUR 100% SAMA
         */
        $modules = collect($response->json('data.modules') ?? [])
        ->map(function ($m) {

            $m = (object) $m;

            // 🔥 FIX UTAMA
            $m->module = isset($m->module)
                ? (object) $m->module
                : null;

            $m->teacher = isset($m->teacher)
                ? (object) $m->teacher
                : null;

            $m->lessons = isset($m->lessons)
                ? collect($m->lessons)->map(fn ($l) => (object) $l)
                : collect();

            return $m;
        });


        return view('siswa.kursus.index', compact('modules'));
    }
}
