<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\SemesterProgram;
use App\Models\Subject;
use App\Models\SchoolProfile;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use App\Models\AnnualProgram; // Memanggil model Prota

class SemesterProgramController extends Controller
{
    /**
     * MENAMPILKAN HALAMAN UTAMA (TABEL)
     */
    public function index()
    {
        $user = Auth::user();
        
        // 1. Data Referensi untuk Dropdown (Modal Tambah)
        // Admin Mapel/Super Admin butuh semua mapel untuk pilihan
        if ($user->role == 'super_admin') {
            $subjects = Subject::all();
        } else {
            // Guru/Admin Mapel hanya melihat mapel yg mereka ampu
            $subjects = $user->subjects; 
        }

        // --- PERBAIKAN DISINI ---
        // 2. Definisi Query Awal (Wajib didefinisikan sebelum IF/ELSE)
        $query = SemesterProgram::with('subject');

        // 3. Filter Data Berdasarkan Role
        if ($user->role == 'super_admin') {
            // Super Admin melihat SEMUA data (Tidak perlu filter)
        } 
        elseif ($user->role == 'admin_mapel') {
            // Admin Mapel melihat data sesuai mapel yang diampunya
            $subjectIds = $user->subjects->pluck('id'); 
            $query->whereIn('subject_id', $subjectIds);
        } 
        else {
            // Guru Mapel hanya melihat data BUATANNYA SENDIRI
            $query->where('user_id', $user->id);
        }

        // 4. Eksekusi Query (Ambil Data)
        $promes = $query->orderBy('created_at', 'desc')->get();

        return view('pages.perangkat.promes.index', compact('promes', 'subjects'));
    }

    /**
     * MENYIMPAN DATA BARU (CREATE)
     */
    /**
     * MENYIMPAN DATA BARU (CREATE MULTIPLE ROWS)
     */
    public function store(Request $request)
    {
        // Validasi input sebagai array (.*)
        $request->validate([
            'subject_id'         => 'required',
            'semester'           => 'required',
            'academic_year'      => 'required',
            'topic.*'            => 'required',
            'allocation_hours.*' => 'required',
        ]);

        // Looping untuk menyimpan semua materi yang di-generate AI / diinput manual
        if ($request->has('topic')) {
            foreach ($request->topic as $index => $topic) {
                if (!empty($topic)) {
                    SemesterProgram::create([
                        'user_id'              => Auth::id(),
                        'subject_id'           => $request->subject_id,
                        'semester'             => $request->semester,
                        
                        'academic_year'        => $request->academic_year,
                        'tahun_ajaran'         => $request->academic_year,
                        
                        'topic'                => $topic,
                        'materi_pokok'         => $topic,
                        
                        'allocation_hours'     => $request->allocation_hours[$index],
                        'alokasi_waktu'        => $request->allocation_hours[$index],
                        
                        // Array distribusi bulanan akan masuk secara spesifik per index
                        'monthly_distribution' => $request->monthly_distribution[$index] ?? [],
                        'bulan_minggu'         => $request->monthly_distribution[$index] ?? [],
                    ]);
                }
            }
        }

        return back()->with('success', 'Data Distribusi Program Semester berhasil disimpan.');
    }
    
    public function update(Request $request, $id)
    {
        $promes = SemesterProgram::findOrFail($id);

        // Validasi Kepemilikan (Guru hanya boleh edit punya sendiri)
        if (Auth::user()->role == 'guru_mapel' && $promes->user_id != Auth::id()) {
            return back()->with('error', 'Anda tidak berhak mengedit data ini.');
        }

        $promes->update([
            'subject_id'         => $request->subject_id,
            'academic_year'      => $request->academic_year,
            'tahun_ajaran'       => $request->academic_year,
            'topic'              => $request->topic,
            'materi_pokok'       => $request->topic,
            'allocation_hours'   => $request->allocation_hours,
            'alokasi_waktu'      => $request->allocation_hours,
            'monthly_distribution' => $request->monthly_distribution ?? [],
            'bulan_minggu'       => $request->monthly_distribution ?? [],
        ]);

        return back()->with('success', 'Data Program Semester berhasil diperbarui.');
    }

    /**
     * HAPUS DATA (DELETE)
     */
    public function destroy($id)
    {
        $promes = SemesterProgram::findOrFail($id);

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

        $promes->delete();

        return back()->with('success', 'Data berhasil dihapus.');
    }

    /**
     * CETAK PDF (PRINT)
     */
    public function print(Request $request)
    {
        $semesterFilter = $request->input('semester', 'Ganjil');
        $subjectId = $request->input('subject_id'); // Filter Mapel Baru
        $tahunAjaran = $request->input('tahun_ajaran');

        if ($semesterFilter == 'Ganjil') {
            $months = ['Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
        } else {
            $months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni'];
        }

        $query = SemesterProgram::with(['subject', 'user'])->where('semester', $semesterFilter);

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

        // Filter Mapel dari Modal
        if ($subjectId) {
            $query->where('subject_id', $subjectId);
        }

        if (!empty($tahunAjaran)) {
            $query->where('academic_year', $tahunAjaran);
        }

        $data = $query->orderBy('created_at', 'asc')->get();

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

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

        return view('pages.perangkat.promes.print', compact(
            'data', 'semesterFilter', 'months', 'tahunAjaran', 
            'school', 'tanggalCetak', 'guru'
        ));
    }
    // --- TAMBAHAN: CETAK SATUAN (SINGLE PRINT) ---
public function printSingle($id)
{
    $promes = SemesterProgram::with(['subject', 'user'])->findOrFail($id);
    
    // Tentukan daftar bulan berdasarkan semester data tersebut
    if ($promes->semester == 'Ganjil') {
        $months = ['Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    } else {
        $months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni'];
    }

    $semesterFilter = $promes->semester;
    $tahunAjaran = $promes->tahun_ajaran ?? $promes->academic_year;
    
    // Bungkus ke collection agar view tetap bisa looping
    $data = collect([$promes]);

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

    $guru = $promes->user ?? Auth::user();
    $tanggalCetak = Carbon::now()->locale('id')->isoFormat('D MMMM Y');

    return view('pages.perangkat.promes.print', compact(
        'data', 'semesterFilter', 'months', 'tahunAjaran', 
        'school', 'tanggalCetak', 'guru'
    ));
}
    // 1. MENGAMBIL DATA DARI PROTA
    public function getProtaData(Request $request)
    {
        $request->validate([
            'subject_id' => 'required',
            'grade_level' => 'required',
            'semester' => 'required'
        ]);

        // Cari materi di Prota yang sesuai dengan Mapel, Kelas, dan Semester
        $protaData = AnnualProgram::where('subject_id', $request->subject_id)
                    ->where('grade_level', $request->grade_level)
                    ->where('semester', $request->semester)
                    ->orderBy('id', 'asc') // Sesuai urutan input
                    ->get(['content_description', 'time_allocation']);

        return response()->json(['status' => 'success', 'data' => $protaData]);
    }

    // 2. GENERATE DISTRIBUSI BULAN & MINGGU VIA AI GROQ
    public function generateAiPromes(Request $request)
    {
        $request->validate([
            'semester' => 'required',
            'materi_list' => 'required|array'
        ]);

        $semester = $request->semester;
        $materiList = json_encode($request->materi_list);

        // Setup konteks bulan berdasarkan semester
        $bulanRange = (strtolower($semester) == 'ganjil') 
            ? "Juli, Agustus, September, Oktober, November, Desember" 
            : "Januari, Februari, Maret, April, Mei, Juni";

        $prompt = "Sebagai perancang Kurikulum Merdeka, buatlah distribusi Program Semester (Promes).
        Semester: {$semester} (Hanya gunakan bulan: {$bulanRange}).
        
        Berikut adalah daftar Materi Pokok beserta Jam Pelajaran (JP)-nya yang sudah urut:
        {$materiList}
        
        Tugas:
        Distribusikan materi tersebut secara berurutan ke dalam bulan dan minggu. 
        - Asumsikan 1 minggu efektif = sekitar 4 hingga 8 JP.
        - Setiap bulan maksimal memiliki angka minggu: 1, 2, 3, 4, 5.
        
        OUTPUT WAJIB FORMAT JSON MURNI SEPERTI INI:
        {
            \"distribusi_promes\": [
                {
                    \"materi_pokok\": \"Nama Materi...\",
                    \"alokasi_jp\": 12,
                    \"jadwal\": {
                        \"Juli\": [3, 4],
                        \"Agustus\": [1]
                    }
                }
            ]
        }";

        try {
            $apiKey = env('GROQ_API_KEY'); 
            $model = env('GROQ_MODEL', 'llama-3.3-70b-versatile');

            $response = Http::withOptions(['verify' => false])
                ->withToken($apiKey)
                ->post('https://api.groq.com/openai/v1/chat/completions', [
                'model' => $model, 
                'response_format' => ['type' => 'json_object'],
                'messages' => [
                    ['role' => 'system', 'content' => 'Kamu asisten API penjadwalan. Balas hanya dengan JSON valid.'],
                    ['role' => 'user', 'content' => $prompt]
                ],
                'temperature' => 0.1, // Dibuat sangat rendah agar urutannya matematis dan logis
            ]);

            if ($response->successful()) {
                $resultText = $response->json()['choices'][0]['message']['content'];
                $data = json_decode($resultText, true);

                if (isset($data['distribusi_promes'])) {
                    return response()->json([
                        'status' => 'success',
                        'results' => $data['distribusi_promes']
                    ]);
                }
            }

            return response()->json(['status' => 'error', 'message' => 'Format AI tidak sesuai.']);

        } catch (\Throwable $e) {
            return response()->json(['status' => 'error', 'message' => 'Server Error: ' . $e->getMessage()]);
        }
    }
}