<?php

namespace App\Http\Controllers;

use App\Models\LearningModule;
use App\Models\Subject;
use App\Models\LearningObjective;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http; // TAMBAHAN: Diperlukan untuk fitur AI

class LearningModuleController extends Controller
{
    // --- 1. HALAMAN UTAMA (INDEX) - (VERSI LAMA) ---
    public function index()
    {
        $user = Auth::user();
        $query = LearningModule::with('subject');

        if ($user->role == 'super_admin') {
            // Super admin all access
        } elseif ($user->role == 'admin_mapel') {
            $subjectIds = $user->subjects->pluck('id');
            $query->whereIn('subject_id', $subjectIds);
        } else {
            $query->where('user_id', $user->id);
        }

        $modules = $query->orderBy('subject_id', 'asc')
            ->orderBy('grade_level', 'asc')
            ->orderBy('meeting_sequence', 'asc')
            ->latest()
            ->get();

        if ($user->role == 'super_admin') {
            $subjects = Subject::all();
        } else {
            $subjects = $user->subjects;
        }

        $atpData = LearningObjective::where('user_id', Auth::id())->get();

        $refModels = ['Problem Based Learning (PBL)', 'Project Based Learning (PjBL)', 'Discovery Learning', 'Inquiry Learning', 'Teaching Factory (Tefa)','Praktikum/Kerja Bengkel'];
        $refMethods = ['Diskusi Kelompok', 'Demonstrasi', 'Presentasi', 'Simulasi', 'Studi Kasus', 'Kunjungan Lapangan', 'Ceramah Interaktif', 'Praktikum/Kerja Bengkel'];        
        $refApproaches = ['Pembelajaran Mendalam','STEM','Saintifik', 'TPACK', 'Konstruktivisme'];
        $refStrategies = [
        'Pembelajaran Berdiferensiasi (Konten/Proses/Produk)',
        'Teaching at the Right Level (TaRL)',
        'Culturally Responsive Teaching (CRT)',
        'Pembelajaran Sosial Emosional (PSE)',
        'Blended Learning (Daring & Luring)',
        'Flipped Classroom',
        'Praktikum'
        ];
        $refEnvironments = [
        'Ruang Kelas',
        'Laboratorium Komputer',
        'Bengkel / Workshop (Praktik)',
        'Perpustakaan',
        'Teaching Factory (TeFa)',
        'Lingkungan Sekolah (Outdoor)',
        'Dunia Kerja / Industri (DUDI)',
        'Platform Daring (LMS)'
        ];
        $refDigital = [
        'Media Presentasi (PPT/Canva)',
        'Video Pembelajaran (YouTube)',
        'LMS (Google Classroom/Moodle)',
        'Kuis Interaktif (Quizizz/Kahoot)',
        'Simulasi Virtual ',
        'Papan Tulis Digital (Jamboard/Padlet)',
        'Augmented/Virtual Reality (AR/VR)',
        'Tidak Menggunakan Perangkat Digital'
        ];

        $refProfil = [
            'Keimanan & Ketakwaan', 'Kewargaan', 'Penalaran Kritis', 
            'Kreativitas', 'Kolaborasi', 'Kemandirian', 'Kesehatan', 'Komunikasi'
        ];

        return view('pages.perangkat.modul.index', compact(
        'modules', 'subjects', 'atpData', 
        'refModels', 'refMethods', 'refApproaches', 'refProfil',
        'refStrategies', 'refEnvironments', 'refDigital'
        ));
    }

    // --- 2. SIMPAN DATA (STORE) - (VERSI LAMA) ---
    public function store(Request $request)
    {
        if (Auth::user()->role == 'admin_mapel') {
            return back()->with('error', 'Maaf, Admin Mapel tidak memiliki akses untuk menambah data baru.');
        }

        $request->validate([
            'subject_id' => 'required',
            'grade_level' => 'required',
            'meeting_sequence' => 'required|numeric',
            'activity_initial' => 'required',
            'learning_objective_id' => 'required', 
        ]);

        // Ambil Data ATP/TP
        $atp = LearningObjective::findOrFail($request->learning_objective_id);

        LearningModule::create([
            'user_id' => Auth::id(),
            'subject_id' => $request->subject_id,
            'grade_level' => $request->grade_level,
            'semester' => $request->semester,
            'profil_pelajar_pancasila' => $request->profil_pelajar_pancasila,
            
            'elemen' => $request->elemen,
            'meeting_sequence' => $request->meeting_sequence,
            'allocation_jp' => $request->allocation_jp,
            'duration_minutes' => $request->duration_minutes,
            
            // PERBAIKAN: Sesuai nama kolom di tabel learning_objectives
            'cp_text' => $atp->learning_outcome, 
            'tp_text' => $atp->objective_description, 

            'topic' => $request->topic,
            
            'model_learning' => $request->model_learning,
            'method_learning' => $request->method_learning,
            'approach_learning' => $request->approach_learning,
            'strategy_learning' => $request->strategy_learning,
            'partnership' => $request->partnership,
            
            'learning_environment' => $request->learning_environment,
            'digital_usage' => $request->digital_usage,
            
            'activity_initial' => $request->activity_initial,
            'activity_core_understand' => $request->activity_core_understand,
            'activity_core_apply' => $request->activity_core_apply,
            'activity_core_reflect' => $request->activity_core_reflect,
            'activity_closing' => $request->activity_closing,
        ]);

        return back()->with('success', 'Modul Ajar berhasil dibuat!');
    }

    // --- 3. UPDATE DATA - (VERSI LAMA) ---
    public function update(Request $request, $id)
    {
        $modul = LearningModule::findOrFail($id);

        if (Auth::user()->role == 'guru_mapel' && $modul->user_id != Auth::id()) {
            return back()->with('error', 'Anda tidak berhak mengedit modul ini.');
        }

        $request->validate([
            'subject_id' => 'required',
            'grade_level' => 'required',
            'meeting_sequence' => 'required|numeric',
            'activity_initial' => 'required',
        ]);

        $dataToUpdate = $request->all();

        // JIKA USER MENGUBAH CP/TP
        if ($request->has('learning_objective_id') && $request->learning_objective_id != null) {
            $atp = LearningObjective::findOrFail($request->learning_objective_id);
            
            // PERBAIKAN ERROR DI SINI: Gunakan nama kolom yang benar
            $dataToUpdate['cp_text'] = $atp->learning_outcome; // Sebelumnya $atp->cp (Salah)
            $dataToUpdate['tp_text'] = $atp->objective_description; // Sebelumnya $atp->tp (Salah)
        }

        $modul->update($dataToUpdate);

        return back()->with('success', 'Modul Ajar berhasil diperbarui!');
    }

    // --- 4. HAPUS DATA - (VERSI LAMA) ---
    public function destroy($id)
    {
        $modul = LearningModule::findOrFail($id);

        if (Auth::user()->role == 'guru_mapel' && $modul->user_id != Auth::id()) {
            return back()->with('error', 'Anda tidak berhak menghapus modul ini.');
        }

        $modul->delete();
        return back()->with('success', 'Modul dihapus!');
    }

    // --- 5. API HELPER (JSON UNTUK DROPDOWN) - (VERSI LAMA) ---
    public function getCP($subjectId)
    {
        // Perbaikan: Jangan ambil 'id', karena 1 CP bisa memiliki banyak baris TP.
        // Kita Grouping berdasarkan teks CP dan Fase-nya.
        $data = LearningObjective::where('subject_id', $subjectId)
                    ->select('learning_outcome', 'phase')
                    ->groupBy('learning_outcome', 'phase')
                    ->get();

        return response()->json($data);
    }

    public function getTP(Request $request)
    {
        // Ambil TP berdasarkan Teks CP yang dipilih
        $tp = LearningObjective::where('learning_outcome', $request->cp_name)
                ->where('subject_id', $request->subject_id)
                ->select('id', 'objective_description')
                ->get();
                
        return response()->json($tp);
    }

    // --- 6. CETAK PDF (BULK) - (VERSI LAMA) ---
    public function printBulk(Request $request)
    {
        $request->validate([
            'module_ids' => 'required|array|min:1',
            'print_date' => 'nullable|date', // Validasi tanggal
        ]);

        $user = Auth::user();

        // Query Data
        $query = LearningModule::with(['subject', 'user'])
                ->whereIn('id', $request->module_ids)
                ->orderBy('meeting_sequence', 'asc');

        if ($user->role == 'guru_mapel') {
            $query->where('user_id', $user->id);
        } 
        elseif ($user->role == 'admin_mapel') {
             $subjectIds = $user->subjects->pluck('id');
             $query->whereIn('subject_id', $subjectIds);
        }

        $data = $query->get();

        if($data->isEmpty()) {
            return back()->with('error', 'Tidak ada data modul yang dapat dicetak.');
        }

        // Data Kepala Sekolah
        $school = \App\Models\SchoolProfile::first();
        if (!$school) {
            $school = (object) [
                'principal_name' => '..........................',
                'principal_nip' => '..........................'
            ];
        }

        // --- LOGIKA TANGGAL CETAK ---
        // Jika user memilih tanggal, pakai itu. Jika tidak, pakai hari ini.
        if ($request->has('print_date') && $request->print_date != null) {
            $tanggalCetak = \Carbon\Carbon::parse($request->print_date)->locale('id')->isoFormat('D MMMM Y');
        } else {
            $tanggalCetak = \Carbon\Carbon::now()->locale('id')->isoFormat('D MMMM Y');
        }

        return view('pages.perangkat.modul.print', compact('data', 'school', 'tanggalCetak'));
    }

    // --- 7. FUNGSI AI GENERATOR - (TAMBAHAN DARI CONTROLLER BARU) ---
    // --- 7. FUNGSI AI GENERATOR (UPDATED) ---
    public function generateAISteps(Request $request) 
    {
        $data = $request->all();

        // 1. Validasi Input Utama
        if (empty($data['topic']) || empty($data['model_learning'])) {
            return response()->json(['error' => 'Topik dan Model wajib diisi.'], 400);
        }

        // 2. Cek API Key
        $apiKey = env('GEMINI_API_KEY');
        if (!$apiKey) return response()->json(['error' => 'API Key belum disetting.'], 500);

        // 3. Susun Prompt Lebih Lengkap (Memasukkan semua variabel metodologi)
        // Kita gunakan Null Coalescing Operator (??) agar tidak error jika data kosong
        $subject        = $data['subject_name'] ?? '-';
        $topic          = $data['topic'] ?? '-';
        $model          = $data['model_learning'] ?? '-';
        $method         = $data['method_learning'] ?? 'Disesuaikan guru';
        $strategy       = $data['strategy_learning'] ?? 'Disesuaikan guru';
        $approach       = $data['approach_learning'] ?? 'Disesuaikan guru';
        $tp_text        = $data['tp_text'] ?? '-';
        $environment    = $data['learning_environment'] ?? '-';
        $digital        = $data['digital_usage'] ?? '-';

        $prompt = "Bertindaklah sebagai Guru Profesional. Buatkan Rincian Langkah Pembelajaran (Kegiatan Awal, Inti, Penutup) untuk Modul Ajar dengan spesifikasi berikut:
        - Mata Pelajaran: $subject
        - Topik Materi: $topic
        - Tujuan Pembelajaran (TP): $tp_text
        - Model Pembelajaran: $model
        - Metode: $method
        - Strategi: $strategy
        - Pendekatan: $approach
        - Lingkungan belajar : $environment
        - Pendekatan Digital : $digital

        INSTRUKSI KHUSUS FORMATTING:
        1. Hasilkan output dalam format JSON murni (tanpa markdown ```json).
        2. Key JSON wajib: 'activity_initial', 'activity_core_understand', 'activity_core_apply', 'activity_core_reflect', 'activity_closing'.
        3. Gaya Bahasa: Operasional, instruktif untuk guru, dan detail.
        4. Jangan gunakan tanda bintang (**) untuk menebalkan teks. Gunakan penomoran biasa (1., 2., 3.) atau huruf (a., b., c.).
        5. Pastikan langkah-langkahnya mengintegrasikan Metode '$method', Strategi '$strategy', Pendekatan '$approach', Lingkungan belajar '$environment', dan Pemanfaatan digital '$digital' yang dipilih.
        ";

        // 4. URL Endpoint
        $url = "[https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=](https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=)" . $apiKey;

        try {
            // 5. Request ke Google
            $response = Http::withOptions(['verify' => false, 'timeout' => 60])
                ->withHeaders(['Content-Type' => 'application/json'])
                ->post($url, [
                    "contents" => [["parts" => [["text" => $prompt]]]]
                ]);

            if ($response->successful()) {
                $result = $response->json();
                $text = $result['candidates'][0]['content']['parts'][0]['text'] ?? '';
                
                // Bersihkan Markdown JSON & Tanda Bintang jika masih ada
                $cleanText = str_replace(['```json', '```', '**'], '', $text);
                
                $json = json_decode($cleanText, true);

                if (json_last_error() === JSON_ERROR_NONE) {
                    return response()->json($json);
                }
                return response()->json(['error' => 'Format AI rusak (Bukan JSON). Coba lagi.'], 500);
            }
            
            return response()->json(['error' => 'Gagal dari Google: ' . $response->status() . ' - ' . $response->body()], 500);

        } catch (\Exception $e) {
            return response()->json(['error' => 'Koneksi Error: ' . $e->getMessage()], 500);
        }
    }
    // --- 6.5 CETAK SATUAN (SINGLE PRINT) ---
public function printSingle($id)
{
    $modul = LearningModule::with(['subject', 'user'])->findOrFail($id);
    
    // Bungkus dalam array agar kompatibel dengan view print (yang menggunakan loop @foreach($data))
    $data = collect([$modul]);

    $school = \App\Models\SchoolProfile::first() ?? (object) [
        'principal_name' => '..........................',
        'principal_nip' => '..........................'
    ];

    $tanggalCetak = \Carbon\Carbon::now()->locale('id')->isoFormat('D MMMM Y');

    return view('pages.perangkat.modul.print', compact('data', 'school', 'tanggalCetak'));
}
    public function getNextMeeting(Request $request)
    {
        $subjectId = $request->query('subject_id');
        $gradeLevel = $request->query('grade_level');
        $semester = $request->query('semester'); // TAMBAHAN: Ambil data semester
        $modelLearning = $request->query('model_learning', ''); 

        // Jika mapel, kelas, atau semester belum dipilih, default kembalikan 1
        if (!$subjectId || !$gradeLevel || !$semester) {
            return response()->json(['next_meeting' => 1]);
        }

        $query = LearningModule::where('subject_id', $subjectId)
            ->where('grade_level', $gradeLevel)
            ->where('semester', $semester); // TAMBAHAN: Filter berdasarkan semester

        // Cek apakah model yang dipilih adalah Praktik
        $isPraktikum = (strpos(strtolower($modelLearning), 'praktikum') !== false || 
                        strpos(strtolower($modelLearning), 'kerja bengkel') !== false);

        if ($isPraktikum) {
            // Jika praktik, cari nomor pertemuan tertinggi KHUSUS di modul praktik
            $query->where(function($q) {
                $q->where('model_learning', 'LIKE', '%praktikum%')
                  ->orWhere('model_learning', 'LIKE', '%kerja bengkel%');
            });
        } else {
            // Jika teori, pastikan benar-benar terpisah dari praktik
            $query->where(function($q) {
                $q->whereNull('model_learning')
                  ->orWhere(function($sub) {
                      $sub->where('model_learning', 'NOT LIKE', '%praktikum%')
                          ->where('model_learning', 'NOT LIKE', '%kerja bengkel%');
                  });
            });
        }

        $lastMeeting = $query->max('meeting_sequence');
        
        // Jika sudah ada modul, tambah 1. Jika belum, mulai dari 1.
        $nextMeeting = $lastMeeting ? $lastMeeting + 1 : 1;

        return response()->json(['next_meeting' => $nextMeeting]);
    }
}