<?php

namespace App\Http\Controllers;

use App\Models\Plant;
use App\Models\VehicleEntry;
use Illuminate\Http\Request;
use Carbon\Carbon;

class VehicleController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    public function storeVehicleEntry(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');

        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response('ERROR: Unauthorized', 403)
                ->header('Content-Type', 'text/plain');
        }

        $plantCode = $request->header('plant-code');

        if(!$plantCode){
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 404);
        }

        if (!ctype_digit((string) $plantCode)) {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "plant code must be $plantCode a numeric value",
            ], 404);
        }

        $plantCod = Plant::where('code', $plantCode)->first();

        if(!$plantCod){
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Plant code $plantCode not found!",
            ], 404);
        }

        $plantId = $plantCod->id;

        // $data = $request->all();

        $data = $request->json()->all();

        $results = [];

        foreach ($data as $item) {

            $uuid = $item['uuid'] ?? '';
            $vehicleNo = trim($item['vehicle_number'] ?? '');
            $entryTimeRaw = $item['entry_time'] ?? '';
            $exitTimeRaw = $item['exit_time'] ?? '';
            $duration = $item['duration'] ?? '';
            $type = $item['type'] ?? '';

            if (!$vehicleNo) {

                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Vehicle number can't be empty!"
                ];

                continue;
            }
            elseif (strlen($vehicleNo) < 8) {

                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Vehicle number '$vehicleNo' must be at least 8 characters long"
                ];

                continue;
            }
            elseif (!$entryTimeRaw) {

                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Entry time can't be empty!"
                ];

                continue;
            }
            elseif (!$type) {

                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Type can't be empty!"
                ];

                continue;
            }
            elseif ($entryTimeRaw && !Carbon::hasFormat($entryTimeRaw, 'd/m/Y h:i:s A')) {
                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Invalid Entry time format $entryTimeRaw. Expected dd/mm/yyyy hh:mm:ss AM/PM"
                ];
                continue;
            }
            else if ($exitTimeRaw && !Carbon::hasFormat($exitTimeRaw, 'd/m/Y h:i:s A')) {

                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Invalid Exit time format $exitTimeRaw. Expected dd/mm/yyyy hh:mm:ss AM/PM"
                ];
                continue;
            }
            elseif ($duration && !preg_match('/^\d{2}:\d{2}:\d{2}$/', $duration)) {

                $results[] = [
                    'uuid' => $uuid,
                    'status_code' => 'ERROR',
                    'status_description' => "Invalid duration format $duration"
                ];
                continue;
            }
        }

        if(!empty($results)){
            return response()->json($results, 404);
        }

        foreach ($data as $item) {

            $uuid = $item['uuid'] ?? '';
            // $vehicleNo = strtoupper(trim($item['vehicle_number'] ?? ''));
            $vehicleNo = strtoupper(
                str_replace(' ', '', trim($item['vehicle_number'] ?? ''))
            );
            $entryTimeRaw  = $item['entry_time'] ?? '';
            $exitTimeRaw   = $item['exit_time'] ?? '';
            $duration = $item['duration'] ?? '';
            $type = $item['type'] ?? '';

            $manualVehicles = [
                'TN01KK0004',
                'TN01KK0001',
            ];

            $boomOpened = in_array($vehicleNo, $manualVehicles) ? 'Manual' : 'Auto';

            if(!empty($entryTimeRaw)){
                $entryTime = $entryTimeRaw
                ? Carbon::createFromFormat('d/m/Y h:i:s A', $entryTimeRaw)
                : null;
            }

            $exitTime = null;

            if(!empty($exitTimeRaw)){

                $exitTime = $exitTimeRaw
                ? Carbon::createFromFormat('d/m/Y h:i:s A', $exitTimeRaw)
                : null;
            }

            if (
                empty($duration) &&
                !empty($entryTime) &&
                !empty($exitTime)
            ) {
                $entry = Carbon::parse($entryTime); // 2026-05-22 16:13:35
                $exit  = Carbon::parse($exitTime);  // 2026-05-25 14:17:29

                $totalSeconds = $entry->diffInSeconds($exit);

                $hours = floor($totalSeconds / 3600);
                $minutes = floor(($totalSeconds % 3600) / 60);
                $seconds = $totalSeconds % 60;

                $duration = sprintf(
                    '%02d:%02d:%02d',
                    $hours,
                    $minutes,
                    $seconds
                );
            }

            $record = VehicleEntry::updateOrInsert(
                [
                    'plant_id' => $plantId,
                    'uuid' => $uuid
                ],
                [
                    'vehicle_number' => $vehicleNo,
                    'boom_opened'    => $boomOpened,
                    'entry_time'     => $entryTime,
                    'exit_time'      => $exitTime ?? null,
                    'duration'       => $duration ?: null,
                    'type'           => $type,
                    'updated_at'     => now(),
                    'created_at'     => now(),
                ]
            );
        }

        if($record){
            return response()->json([
                'status'  => 'SUCCESS',
                'status_description' => 'Vehicle entry inserted successfully'
            ], 200);
        }
        else
        {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => 'Failed to insert record in the table vehicle entry'
            ], 404);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
