<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Session;
use DB;

class Leave extends Model
{
    use HasFactory;

    protected $fillable = [
        'staff_id',
        'employee_name',
        'leave_type',
        'remaining_leave',
        'date_from',
        'date_to',
        'number_of_day',
        'leave_date',
        'leave_day',
        'status',
        'reason',
        'approved_by',
    ];

    /** Save Record Leave or Update */
    public function applyLeave(Request $request)
    {
        // Validate the request
        $validated = $request->validate([
            'leave_type' => 'required|string',
            'date_from'  => 'required|date',
            'date_to'    => 'required|date|after_or_equal:date_from',
            'reason'     => 'required|string',
            'number_of_day' => 'required|integer|min:1',
            'leave_date' => 'required|array',
            'select_leave_day' => 'required|array',
        ]);

        try {
            // Handle employee data assignment from session or input
            if (!empty($request->employee_name)) {
                $employee_name = "Ciby";
                $employee_id   = 5;
            } else {
                $employee_name = Session::get('name');
                $employee_id   = Session::get('user_id');
            }

            // Handle leave creation or update
            $leave = Leave::updateOrCreate(
                ['id' => $request->id_record],
                [
                    'staff_id'        => $employee_id,
                    'employee_name'   => $employee_name,
                    'leave_type'      => $request->leave_type,
                    'remaining_leave' => $request->remaining_leave,
                    'date_from'       => $request->date_from,
                    'date_to'         => $request->date_to,
                    'number_of_day'   => $request->number_of_day,
                    'leave_date'      => json_encode($request->leave_date),
                    'leave_day'       => json_encode($request->select_leave_day),
                    'status'          => 'Pending',  // Default status
                    'reason'          => $request->reason,
                    'approved_by'     => Session::get('line_manager'),
                ]
            );

            flash()->success('Leave applied successfully!');
            return redirect()->back();
        } catch (\Exception $e) {
            \Log::error($e);
            flash()->error('Failed to apply leave.');
            return redirect()->back();
        }
    }

    /** Delete Record */
    public function deleteRecord(Request $request)
    {
        try {
            // Attempt to delete the record
            Leave::destroy($request->id_record);

            flash()->success('Leaves deleted successfully!');
            return redirect()->back();
        } catch (\Exception $e) {
            \Log::error($e);
            flash()->error('Failed to delete leave.');
            return redirect()->back();
        }
    }
}
