<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;


use App\Models\Holiday;
use Carbon\Carbon;

class SuperAdminHolidayController extends Controller
{
    public function index()
    {
        $holidays = Holiday::orderBy('date', 'asc')->get();
        return view('superadmin.employee.holiday', compact('holidays'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'date' => 'required|date|unique:holidays,date',
            'type' => 'required'
        ]);

        $date = Carbon::parse($request->date);
        
        Holiday::create([
            'name' => $request->name,
            'date' => $request->date,
            'day' => $date->format('l'), // Auto-calculate Day
            'type' => $request->type,
            'description' => $request->description
        ]);

        return redirect()->back()->with('success', 'Holiday added successfully.');
    }

    public function update(Request $request, $id)
    {
        $holiday = Holiday::findOrFail($id);
        
        $request->validate([
            'name' => 'required|string',
            'date' => 'required|date|unique:holidays,date,' . $id,
            'type' => 'required'
        ]);

        $date = Carbon::parse($request->date);

        $holiday->update([
            'name' => $request->name,
            'date' => $request->date,
            'day' => $date->format('l'),
            'type' => $request->type,
            'description' => $request->description
        ]);

        return redirect()->back()->with('success', 'Holiday updated successfully.');
    }

    public function destroy($id)
    {
        Holiday::findOrFail($id)->delete();
        return response()->json(['success' => true]);
    }
}
