<?php

namespace App\Http\Controllers\Karyawan;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\IzinSakit;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class IzinSakitController extends Controller
{
    // ── INDEX — daftar semua pengajuan izin/sakit milik karyawan ──────────
    public function index()
    {
        $karyawan = Auth::user()->karyawan;

        $izinSakits = IzinSakit::where('karyawan_id', $karyawan->id)
            ->orderBy('created_at', 'desc')
            ->get();

        return view('karyawan.izin-sakit.index', compact('izinSakits'));
    }

    // ── CREATE — form pengajuan baru ──────────────────────────────────────
    public function create()
    {
        return view('karyawan.izin-sakit.create');
    }

    // ── STORE — simpan pengajuan ──────────────────────────────────────────
    public function store(Request $request)
    {
        $request->validate([
            'jenis'          => 'required|in:izin,sakit',
            'tanggal_mulai'  => 'required|date',
            'tanggal_selesai'=> 'required|date|after_or_equal:tanggal_mulai',
            'keterangan'     => 'nullable|string|max:500',
            'bukti_file'     => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048',
        ]);

        $karyawan = Auth::user()->karyawan;

        $path = null;
        if ($request->hasFile('bukti_file')) {
            $path = $request->file('bukti_file')->store('izin-bukti', 'public');
        }

        IzinSakit::create([
            'karyawan_id'    => $karyawan->id,
            'jenis'          => $request->jenis,
            'tanggal_mulai'  => $request->tanggal_mulai,
            'tanggal_selesai'=> $request->tanggal_selesai,
            'keterangan'     => $request->keterangan,
            'bukti_file'     => $path,
            'status'         => 'pending',
        ]);

        return redirect()->route('karyawan.izin-sakit.index')
            ->with('success', 'Pengajuan berhasil dikirim dan menunggu persetujuan.');
    }

    // ── SHOW — detail satu pengajuan ─────────────────────────────────────
    public function show($id)
    {
        $karyawan   = Auth::user()->karyawan;
        $izinSakit  = IzinSakit::where('karyawan_id', $karyawan->id)->findOrFail($id);

        return view('karyawan.izin-sakit.show', compact('izinSakit'));
    }
}