<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\LeaveLedger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class LeaveLedgerController extends Controller
{
    public function index(Request $request)
    {
        //
        $employee = Auth::user();

        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $dealership = $request->input('dealership', '');

        $keyword = str_replace(" ", "%", $keyword);

        DB::enableQueryLog();

        $data = LeaveLedger::with([
            'employee' => fn($employee) => $employee->select('id', 'employee_id', DB::raw('CONCAT(lastname, ", ", firstname) as full_name')),
            'leave_type' => fn($leave_type) => $leave_type->select('id', 'name', 'enabled'),
        ])
        ->select(
            'id', 
            'employee_id', 
            'company_id', 
            'dealer_id', 
            'leave_id',
            'date_from',
            'date_to', 
            'credits_from', 
            'credits_to', 
            'credit', 
            'hours', 
            'leave_type', 
            'leave_name', 
            'date_applied', 
            )
        ->where(function ($query) use ($keyword) {
            if ($keyword) {
                $query->where('column_name', 'like', "%{$keyword}%");
            }
        })
        ->whereIn('dealer_id', explode(',', $dealership));

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }
        
        $data = $data->paginate(10000);

        return response()->json($data);
    }

    public function show(Request $request, $employee_id){
        $data = LeaveLedger::where('employee_id', $employee_id)->get();
        
        return response()->json($data);
    }
}
