<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class JadwalSidangController extends Controller
{
    public function index(Request $request)
    {
        $jadwal = json_decode(File::get(public_path('assets/json/backend/jadwal.json')), true);

        // Filter by document type if provided in request
        $documentType = $request->input('document_type');
        if ($documentType) {
            $jadwal = array_values(array_filter($jadwal, function($item) use ($documentType) {
                return isset($item['documentType']) && $item['documentType'] === $documentType;
            }));
        }

        return view('penjadwalan.jadwal_sidang', compact('jadwal'));
    }

    public function create(Request $request)
    {
        // Handle form submission for creating new schedule
        if ($request->isMethod('post')) {
            $jadwal = json_decode(File::get(public_path('assets/json/backend/jadwal.json')), true);

            // Get the highest ID and increment by 1
            $maxId = 0;
            foreach ($jadwal as $item) {
                if (isset($item['id']) && $item['id'] > $maxId) {
                    $maxId = $item['id'];
                }
            }

            // Create new jadwal item
            $newJadwal = [
                'id' => $maxId + 1,
                'title' => $request->input('title'),
                'start' => $request->input('start_date'),
                'end' => $request->input('end_date'),
                'allDay' => $request->input('all_day', false),
                'documentType' => $request->input('document_type'),
                'description' => $request->input('description', '')
            ];

            // Add to existing jadwal
            $jadwal[] = $newJadwal;

            // Save back to JSON file
            File::put(public_path('assets/json/backend/jadwal.json'), json_encode($jadwal, JSON_PRETTY_PRINT));

            return redirect()->route('jadwal.index')->with('success', 'Jadwal berhasil ditambahkan');
        }

        return view('penjadwalan.create_jadwal');
    }

}
