<?php

namespace App\Http\Controllers\HRM;

use App\Http\Controllers\Controller;
use App\Models\LeaveType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class LeaveTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $companyId = $request->session()->get('company_id');
        $query = LeaveType::where('company_id', $companyId);

        // Apply filters if provided
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('name_en', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%");
            });
        }

        $leaveTypes = $query->orderBy('name')->paginate(10);

        return view('hrm.leave_types.index', compact('leaveTypes'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('hrm.leave_types.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'name_en' => 'nullable|string|max:255',
            'code' => 'nullable|string|max:50',
            'days_per_year' => 'required|integer|min:0',
            'is_paid' => 'boolean',
            'carry_forward' => 'boolean',
            'max_carry_forward_days' => 'nullable|integer|min:0',
            'requires_attachment' => 'boolean',
            'description' => 'nullable|string',
            'status' => 'required|in:active,inactive',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $companyId = $request->session()->get('company_id');

        $leaveType = new LeaveType();
        $leaveType->company_id = $companyId;
        $leaveType->name = $request->name;
        $leaveType->name_en = $request->name_en;
        $leaveType->code = $request->code;
        $leaveType->days_per_year = $request->days_per_year;
        $leaveType->is_paid = $request->has('is_paid');
        $leaveType->carry_forward = $request->has('carry_forward');
        $leaveType->max_carry_forward_days = $request->max_carry_forward_days ?? 0;
        $leaveType->requires_attachment = $request->has('requires_attachment');
        $leaveType->description = $request->description;
        $leaveType->status = $request->status;
        $leaveType->created_by = Auth::id();
        $leaveType->save();

        return redirect()->route('hrm.leave_types.index')
            ->with('success', 'Leave type created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $leaveType = LeaveType::findOrFail($id);

        // Check if leave type belongs to the current company
        $companyId = session('company_id');
        if ($leaveType->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        return view('hrm.leave_types.show', compact('leaveType'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $companyId = $request->session()->get('company_id');
        $leaveType = LeaveType::findOrFail($id);

        // Check if leave type belongs to the current company
        if ($leaveType->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        return view('hrm.leave_types.edit', compact('leaveType'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $leaveType = LeaveType::findOrFail($id);

        // Check if leave type belongs to the current company
        $companyId = $request->session()->get('company_id');
        if ($leaveType->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'name_en' => 'nullable|string|max:255',
            'code' => 'nullable|string|max:50',
            'days_per_year' => 'required|integer|min:0',
            'is_paid' => 'boolean',
            'carry_forward' => 'boolean',
            'max_carry_forward_days' => 'nullable|integer|min:0',
            'requires_attachment' => 'boolean',
            'description' => 'nullable|string',
            'status' => 'required|in:active,inactive',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $leaveType->name = $request->name;
        $leaveType->name_en = $request->name_en;
        $leaveType->code = $request->code;
        $leaveType->days_per_year = $request->days_per_year;
        $leaveType->is_paid = $request->has('is_paid');
        $leaveType->carry_forward = $request->has('carry_forward');
        $leaveType->max_carry_forward_days = $request->max_carry_forward_days ?? 0;
        $leaveType->requires_attachment = $request->has('requires_attachment');
        $leaveType->description = $request->description;
        $leaveType->status = $request->status;
        $leaveType->updated_by = Auth::id();
        $leaveType->save();

        return redirect()->route('hrm.leave_types.index')
            ->with('success', 'Leave type updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $leaveType = LeaveType::findOrFail($id);

        // Check if leave type belongs to the current company
        $companyId = $request->session()->get('company_id');
        if ($leaveType->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        // Check if leave type is being used in any leave requests
        if ($leaveType->leaves()->exists()) {
            return redirect()->route('hrm.leave_types.index')
                ->with('error', 'Cannot delete leave type as it is being used in leave requests.');
        }

        $leaveType->delete();

        return redirect()->route('hrm.leave_types.index')
            ->with('success', 'Leave type deleted successfully.');
    }
}
