<?php

namespace App\Http\Controllers\Admin;

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

class LeaveController extends Controller
{
    public function store(Request $request)
    {
        $employee = DB::table('employees')
            ->where('id', $request->employee_id)
            ->first();

        $setting = DB::table('leave_settings')
            ->where('designation', $employee->designation)
            ->first();

        $totalEmployees = DB::table('employees')
            ->where('designation', $employee->designation)
            ->count();

        $leaveCount = DB::table('leaves')
            ->join('employees', 'employees.id', '=', 'leaves.employee_id')
            ->where('employees.designation', $employee->designation)
            ->where('leaves.status', 'approved')
            ->whereDate('from_date', '<=', $request->from_date)
            ->whereDate('to_date', '>=', $request->from_date)
            ->count();

        $remaining = $totalEmployees - $leaveCount;

        $status = 'approved';
        $message = 'Leave approved automatically';

        if ($setting && $remaining <= $setting->min_employees) {
            $status = 'rejected';
            $message = "Cannot apply leave. Only {$remaining} employees available";
        }

        DB::table('leaves')->insert([
            'employee_id' => $request->employee_id,
            'from_date' => $request->from_date,
            'to_date' => $request->to_date,
            'reason' => $request->reason,
            'status' => $status,
            'message' => $message
        ]);

        return back()->with($status == 'approved' ? 'success' : 'error', $message);
    }
    // 🔹 Approve Leave
    public function approve($id)
    {
        DB::table('leaves')
            ->where('id', $id)
            ->update(['status' => 'approved']);

        return back()->with('success','Leave Approved');
    }

    // 🔹 Reject Leave
    public function reject($id)
    {
        DB::table('leaves')
            ->where('id', $id)
            ->update(['status' => 'rejected']);

        return back()->with('success','Leave Rejected');
    }
}
