<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Form;
use Carbon\Carbon;

class FormController extends Controller
{
    public function pendaftaran()
    {
        
    if (auth()->user()->role == 'karyawan' || auth()->user()->role == 'admin') {
        $forms = Form::latest()->paginate(10); 
    } else {
        $forms = Form::where('status', 'Dibuka')->latest()->paginate(10);
    }
    
        return view('form', compact('forms'));
    }

    public function create()
    {
        return view('form.create');
    }

    public function store(Request $request)
    {
       $rules = [
        'nama_form' => 'required|string|max:255',
        'jenis_form' => 'required|in:penurunan,pengangsuran',
        'semester' => 'required|in:Ganjil,Genap',
        'tahun' => 'required|digits:4|integer|min:2018|max:' . (date('Y') + 1),
        'tanggal_pembukaan' => 'required|date',
        'tanggal_penutupan' => 'required|date|after:tanggal_pembukaan',
        'tanggal_verifikasi' => 'required|date|after:tanggal_penutupan',
        'tanggal_pengumuman' => 'required|date|after:tanggal_verifikasi'
    ];

        $data = [
        'nama_form' => $request->nama_form,
        'jenis_form' => $request->jenis_form,
        'semester' => $request->semester,
        'tahun' => $request->tahun,
        'tanggal_pembuatan' => now(),
        'status' => $request->has('status') ? 'Dibuka' : 'Ditutup',
        'tanggal_pembukaan' => $request->tanggal_pembukaan,
        'tanggal_penutupan' => $request->tanggal_penutupan,
        'tanggal_verifikasi' => $request->tanggal_verifikasi,
        'tanggal_pengumuman' => $request->tanggal_pengumuman
    ];

    // Jika admin, tambahkan validasi kuota
    if (auth()->user()->role == 'admin') {
        $rules['kuota'] = 'required|integer|min:0';
        $data['kuota'] = $request->kuota;
        
        // Set the specific kuota based on jenis_form
        if ($request->jenis_form === 'pengangsuran') {
            $data['kuota_pengangsuran'] = $request->kuota;
            $data['kuota_penurunan'] = 0;
        } else {
            $data['kuota_penurunan'] = $request->kuota;
            $data['kuota_pengangsuran'] = 0;
        }
    }

    $request->validate($rules);

    try {
        Form::create($data);

        return redirect()->route('form.pendaftaran')
            ->with('success', 'Form berhasil dibuat!');
    } catch (\Exception $e) {
        return redirect()->back()
            ->withInput()
            ->with('error', 'Gagal menyimpan form: ' . $e->getMessage());
    }
}

       
    public function edit($id)
    {
        $form = Form::findOrFail($id);
        return view('form.edit', compact('form'));
    }
        
    public function update(Request $request, $id)
    {
        $form = Form::findOrFail($id);

        $rules = [
            'nama_form' => 'required|string|max:255',
            'jenis_form' => 'required|in:penurunan,pengangsuran',
            'semester' => 'required|in:Ganjil,Genap',
            'tahun' => 'required|digits:4|integer|min:2018|max:' . (date('Y') + 1),
            'tanggal_pembukaan' => 'required|date',
            'tanggal_penutupan' => 'required|date|after:tanggal_pembukaan',
            'tanggal_verifikasi' => 'required|date|after:tanggal_penutupan',
            'tanggal_pengumuman' => 'required|date|after:tanggal_verifikasi'
        ];

         $data = [
            'nama_form' => $request->nama_form,
            'jenis_form' => $request->jenis_form,
            'semester' => $request->semester,
            'tahun' => $request->tahun,
            'tanggal_pembukaan' => $request->tanggal_pembukaan,
            'tanggal_penutupan' => $request->tanggal_penutupan,
            'tanggal_verifikasi' => $request->tanggal_verifikasi,
            'tanggal_pengumuman' => $request->tanggal_pengumuman,
            'status' => $request->has('status') ? 'Dibuka' : 'Ditutup' // Handle checkbox
        ];

        if (auth()->user()->role == 'admin') {
        $rules['kuota'] = 'required|integer|min:0';
        $data['kuota'] = $request->kuota;
        
        // Set the specific kuota based on jenis_form
        if ($request->jenis_form === 'pengangsuran') {
            $data['kuota_pengangsuran'] = $request->kuota;
            $data['kuota_penurunan'] = 0;
        } else {
            $data['kuota_penurunan'] = $request->kuota;
            $data['kuota_pengangsuran'] = 0;
        }
    }
       try {
        $request->validate($rules);
        
        $form->update($data);
                
        return redirect()->route('form.pendaftaran')
            ->with('success', 'Formulir berhasil diperbarui.');
    } catch (\Illuminate\Validation\ValidationException $e) {
        return redirect()->back()
            ->withErrors($e->errors())
            ->withInput();
    } catch (\Exception $e) {
        return back()->withInput()
            ->with('error', 'Gagal memperbarui formulir: ' . $e->getMessage());
    }
}

    
    public function toggleStatus($id)
    {
        $form = Form::findOrFail($id);
        $form->status = ($form->status == 'Dibuka') ? 'Ditutup' : 'Dibuka';
        $form->save();

        return redirect()->back()->with('success', 'Status form berhasil diubah.');
    }

    public function destroy($id)    
    {
        $form = Form::findOrFail($id);
        $form->delete();
        return redirect()->route('form.pendaftaran')->with('success', 'Form berhasil dihapus.');
    }

    public function showReductionForm()
    {
        return view('form.penurunan'); 
    }

    public function showInstallmentForm()
    {
        return view('form.pengangsuran'); 
    }

    public function updateQuota(Request $request, Form $form)
{
    $validated = $request->validate([
        'kuota_pengangsuran' => 'nullable|integer|min:0|max:1000',
        'kuota_penurunan' => 'nullable|integer|min:0|max:1000'
    ]);

    try {
        // Only update the fields that were provided
        if ($request->has('kuota_pengangsuran')) {
            $form->kuota_pengangsuran = $request->kuota_pengangsuran;
        }
        
        if ($request->has('kuota_penurunan')) {
            $form->kuota_penurunan = $request->kuota_penurunan;
        }
        
        $form->save();
        
        return back()->with('success', 'Kuota berhasil diperbarui');
    } catch (\Exception $e) {
        return back()->with('error', 'Gagal memperbarui kuota: '.$e->getMessage());
    }
}

}
