<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeOffset;
use App\Models\ExpiredOffset;
use App\Models\OffsetRemaining;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Throwable;

class OffsetRemainingController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');


        // Check if data exists in cache, otherwise execute the query and cache the result
        $data = OffsetRemaining::where(function ($query) use ($keyword) {
                    $keyword = str_replace(" ", "%", $keyword);
                })
                ->when(!empty($sortBy) && !empty($sortType), function ($query) use ($sortBy, $sortType) {
                    $query->orderBy($sortBy, $sortType);
                })
                ->paginate($perPage);                                
            
        return response()->json($data);
    }

    public function offsetExpiration()
    {
        $offsets = EmployeeOffset::where('approved_at', '<', Carbon::now()->subMonths(6))
            ->where('status', 2)
            ->where('expired', 0)
            ->get();

        foreach($offsets as $offset){
            try{

                DB::beginTransaction();

                // Create expiration history
                $status = ExpiredOffset::create([
                    'offset_id' => $offset->id,
                    'employee_id' => $offset->employee_id,
                    'company_id' => $offset->company_id,
                    'dealer_id' => $offset->dealer_id,
                    'date_expired' => date('Y-m-d'),
                    'hours' => $offset->hours,
                ]);

                // Update the offset remaining table
                $updateOffRemaining = OffsetRemaining::where('employee_id', $offset->employee_id)->first();

                $updateOffRemaining->remaining = $updateOffRemaining->remaining - $offset->hours;
                $updateOffRemaining->save();

                // Update the offset to expired
                $updateOffsetToExpired = EmployeeOffset::findOrFail($offset->id);

                $updateOffsetToExpired->expired = true;
                $updateOffsetToExpired->save();

                DB::commit();

            } catch(Throwable $e) {
                DB::rollBack();
                return response()->json([
                    'status' => false,
                    'message' => 'Unable to process request. Please try again.',
                    'data' => $e->getMessage()
                ], Response::HTTP_INTERNAL_SERVER_ERROR);
            }
        }

        return response()->json([
            'status' => true,
            'message' => 'Saved successfully!',
        ], Response::HTTP_CREATED);
    }
}
