<?php

namespace App\Http\Controllers;

use App\Models\Journal;
use App\Models\Subject;
use App\Models\Student;
use App\Models\Schedule; // <--- JANGAN LUPA IMPORT MODEL JADWAL
use App\Models\LearningModule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class JournalController extends Controller
{
   public function index()
    {
        $user = Auth::user();
        
        // HAPUS latest() di sini agar tidak diurutkan berdasarkan tanggal buat
        $query = Journal::with(['subject', 'students']);

        if ($user->role == 'guru_mapel') {
            $query->where('user_id', $user->id);
        }

        // AMBIL DATA LALU URUTKAN (Sort by Mapel Name -> Meeting Sequence)
        $journals = $query->get()->sortBy([
            ['subject.name', 'asc'],       // 1. Kelompokkan/urutkan berdasarkan nama mapel (A-Z)
            ['meeting_sequence', 'asc'],   // 2. Urutkan berdasarkan pertemuan terkecil ke terbesar
        ])->values(); // values() digunakan untuk me-reset index array agar rapi di Blade

        
        // Data Pendukung Dropdown
        // Subjects diambil dari relasi user (jika ada) atau ambil semua
        $subjects = ($user->role == 'guru_mapel') ? ($user->subjects ?? Subject::all()) : Subject::all();

        // PERBAIKAN: Ambil kelas HANYA yang ada di jadwal guru tersebut (Bukan semua kelas di sekolah)
        if ($user->role == 'guru_mapel') {
             $classes = Schedule::where('user_id', $user->id)
                        ->select('class')
                        ->distinct()
                        ->orderBy('class')
                        ->pluck('class');
        } else {
             $classes = Student::select('class')->distinct()->orderBy('class')->pluck('class');
        }

        return view('pages.pembelajaran.jurnal.index', compact('journals', 'subjects', 'classes'));
    }

// --- 1. SIMPAN BARU (DIPERBARUI) ---
    public function store(Request $request)
    {
        // Validasi Input
        $validated = $request->validate([
            'subject_id' => 'required',
            'date'       => 'required|date',
            'class'      => 'required',
            'period'     => 'required|array',
            'meeting_sequence' => 'required',
            'topics'     => 'nullable|array',
            'topic_status' => 'nullable|array', // Validasi input status
            'notes'      => 'nullable',
        ]);

        $validated['user_id'] = Auth::id();
        $validated['period'] = implode(', ', $request->period);

        // --- LOGIKA BARU: GABUNGKAN NAMA MATERI DAN STATUSNYA ---
        $finalTopics = [];
        // Ambil semua status yang dikirim form
        $statuses = $request->input('topic_status', []); 

        if($request->has('topics')) {
            foreach($request->topics as $topicName) {
                // Cari status untuk materi ini di array statuses
                // Jika tidak ada/null, default ke 'full'
                $status = $statuses[$topicName] ?? 'full'; 

                // Simpan sebagai Object/Array: {"name": "Materi A", "status": "partial"}
                $finalTopics[] = [
                    'name' => $topicName,
                    'status' => $status
                ];
            }
        }
        
        // Timpa input 'topics' dengan array baru yang sudah ada statusnya
        $validated['topics'] = $finalTopics;

        // Simpan ke Database
        $journal = Journal::create($validated);

        // Simpan Absensi
        $this->syncAttendance($journal->id, $request->class, $request->student_attendance);

        return back()->with('success', 'Jurnal berhasil ditambahkan');
    }

    // --- 2. UPDATE / EDIT (DIPERBARUI) ---
    public function update(Request $request, $id)
    {
        $journal = Journal::findOrFail($id);

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

        $validated = $request->validate([
            'subject_id' => 'required',
            'date'       => 'required|date',
            'class'      => 'required',
            'period'     => 'required|array',
            'meeting_sequence' => 'required',
            'topics'     => 'nullable|array',
            'topic_status' => 'nullable|array', // Validasi input status
            'notes'      => 'nullable',
        ]);

        $validated['period'] = implode(', ', $request->period);
        
        // --- LOGIKA BARU: GABUNGKAN NAMA MATERI DAN STATUSNYA ---
        $finalTopics = [];
        $statuses = $request->input('topic_status', []); 

        if($request->has('topics')) {
            foreach($request->topics as $topicName) {
                // Ambil status, default 'full'
                $status = $statuses[$topicName] ?? 'full'; 
                
                $finalTopics[] = [
                    'name' => $topicName,
                    'status' => $status
                ];
            }
        }
        $validated['topics'] = $finalTopics;

        // Update Database
        $journal->update($validated);
        $this->syncAttendance($journal->id, $request->class, $request->student_attendance);

        return back()->with('success', 'Jurnal berhasil diperbarui');
    }
    // --- 3. HAPUS ---
    public function destroy($id)
    {
        $journal = Journal::findOrFail($id);
        
        if(Auth::user()->role == 'guru_mapel' && $journal->user_id != Auth::id()) {
             return back()->with('error', 'Akses ditolak.');
        }

        // Hapus Absensi Manual (Jaga-jaga jika di DB tidak set ON DELETE CASCADE)
        DB::table('jurnal_student')->where('jurnal_id', $id)->delete();
        
        $journal->delete();
        return back()->with('success', 'Jurnal dihapus');
    }

    // --- LOGIKA PENYIMPANAN ABSENSI ---
    private function syncAttendance($journalId, $className, $attendanceList)
    {
        // 1. Bersihkan data lama (penting untuk edit)
        DB::table('jurnal_student')->where('jurnal_id', $journalId)->delete();

        // 2. Ambil ID siswa yang "HADIR" dari input form
        // Jika form kosong (tidak ada yg hadir), set array kosong
        $hadirIds = $attendanceList ?? [];

        // 3. Ambil SEMUA siswa di kelas tersebut (untuk mencatat Alpha juga)
        $allStudents = Student::where('class', $className)->pluck('id');

        $insertData = [];
        $now = now();

        foreach($allStudents as $studentId) {
            // Cek status
            $status = in_array($studentId, $hadirIds) ? 'hadir' : 'alpha';

            $insertData[] = [
                'jurnal_id'  => $journalId,
                'student_id' => $studentId,
                'status'     => $status,
                'created_at' => $now,
                'updated_at' => $now,
            ];
        }

        // 4. Insert Batch ke Database
        if (!empty($insertData)) {
            DB::table('jurnal_student')->insert($insertData);
        }
    }

    // --- API HELPER (Untuk Javascript Modal) ---
    

    public function getStudents(Request $request)
    {
        $students = Student::where('class', $request->class)
                    ->orderBy('name')
                    ->get(['id', 'name', 'nis']);      
        return response()->json($students);
    }
    public function getClasses(Request $request)
    {
        // Cari kelas di tabel jadwal yang user_id & subject_id nya cocok
        $classes = Schedule::where('user_id', Auth::id())
                    ->where('subject_id', $request->subject_id)
                    ->select('class')
                    ->distinct()
                    ->orderBy('class')
                    ->pluck('class');
        
        return response()->json($classes);
    }
    public function getTopics(Request $request) 
{
    $grade = explode(' ', $request->kelas)[0] ?? ''; 

    // 1. Ambil semua topik dari Master Data
   $allTopics = LearningModule::where('subject_id', $request->subject_id)
                    ->where('grade_level', 'LIKE', '%' . $grade . '%') 
                    ->orderBy('meeting_sequence', 'asc') 
                    ->get(['id', 'topic', 'meeting_sequence', 'semester', 'model_learning']);

    // 2. Cek Riwayat Jurnal Guru di Kelas & Mapel ini
    $journalHistory = Journal::where('class', $request->kelas)
                ->where('subject_id', $request->subject_id)
                ->where('user_id', Auth::id()) 
                ->get();
    
    $finishedTopics = []; // Daftar materi yang sudah 'full'
    $partialTopics = [];  // Daftar materi yang pernah dibahas 'partial'

    foreach($journalHistory as $j) {
        if(empty($j->topics)) continue;

        foreach($j->topics as $t) {
            // Handle Format Lama (String biasa dianggap Full)
            if(is_string($t)) {
                $finishedTopics[] = $t; 
            } 
            // Handle Format Baru (Array/Object)
            elseif(is_array($t) && isset($t['status'])) {
                if($t['status'] == 'full') {
                    $finishedTopics[] = $t['name'];
                } elseif($t['status'] == 'partial') {
                    $partialTopics[] = $t['name'];
                }
            }
        }
    }

    // 3. Gabungkan status ke daftar topik
    // Logika: Jika materi ada di daftar Finished, maka statusnya 'done'.
    // Jika tidak ada di Finished tapi ada di Partial, statusnya 'ongoing'.
    
    foreach($allTopics as $t) {
        if (in_array($t->topic, $finishedTopics)) {
            $t->history_status = 'done'; // Selesai (Coret & Disable)
        } elseif (in_array($t->topic, $partialTopics)) {
            $t->history_status = 'ongoing'; // Pernah dibahas sebagian
        } else {
            $t->history_status = 'new'; // Belum pernah tersentuh
        }
    }

    return response()->json($allTopics);
}
	public function create()
{
    // Karena form ada di Modal (halaman index), kita redirect ke sana
    // dengan session 'open_modal' agar modal otomatis terbuka
    return redirect()->route('jurnal.index')->with('open_create_modal', true);
}
    // --- API HELPER: AMBIL PERTEMUAN TERAKHIR ---
    public function getLastMeeting(Request $request)
    {
        $subject_id = $request->subject_id;
        $class = $request->class;
        $user_id = Auth::id(); 

        // Cari urutan pertemuan paling besar untuk mapel & kelas ini
        $lastMeeting = Journal::where('user_id', $user_id)
                              ->where('subject_id', $subject_id)
                              ->where('class', $class)
                              ->max('meeting_sequence');

        // Jika belum ada jurnal sama sekali, kembalikan 0
        return response()->json(['last_meeting' => $lastMeeting ?? 0]);
    }
}