<?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();

        $vehicleNo = $data['vehicle_number'] ?? '';
        $entryTimeRaw  = $data['entry_time'] ?? '';
        $exitTimeRaw   = $data['exit_time'] ?? '';
        $duration = $data['duration'] ?? '';
        $type = $data['type'] ?? '';

        if(!$vehicleNo)
        {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Vehicle number cant't be empty!",
            ], 404);
        }
        else if (strlen($vehicleNo) < 8) {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "vehicle number '$vehicleNo' must be at least 8 characters long",
            ], 404);
        }
        else if(!$entryTimeRaw)
        {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Entry time cant't be empty!",
            ], 404);
        }
        else if(!$exitTimeRaw)
        {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Exit time cant't be empty!",
            ], 404);
        }
        else if(!$duration)
        {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Duration cant't be empty!",
            ], 404);
        }
        else if(!$type)
        {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "type cant't be empty!",
            ], 404);
        }


        if ($entryTimeRaw && !Carbon::hasFormat($entryTimeRaw, 'd/m/Y h:i:s A')) {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Invalid Entry time format $entryTimeRaw. Expected dd/mm/yyyy hh:mm:ss AM/PM",
            ], 404);
        }
        else if ($exitTimeRaw && !Carbon::hasFormat($exitTimeRaw, 'd/m/Y h:i:s A')) {
            return response()->json([
                'status'  => 'ERROR',
                'status_description' => "Invalid Exit time format $exitTimeRaw. Expected dd/mm/yyyy hh:mm:ss AM/PM",
            ], 404);
        }
        else if ($duration && !preg_match('/^\d{2}:\d{2}:\d{2}$/', $duration)) {
            return response()->json([
                'status'  => 'error',
                'status_description' => "Invalid duration format $duration. Expected HH:MM:SS",
            ], 404);
        }

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

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

        VehicleEntry::insert([
            'plant_id'      => $plantId,
            'vehicle_number' => $vehicleNo,
            'entry_time'     => $entryTime,
            'exit_time'      => $exitTime,
            'duration'       => $duration,
            'type'           => $type,
            'created_at'     => now(),
            'updated_at'     => now(),
        ]);

        return response()->json([
            'status'  => 'success',
            'status_description' => 'Vehicle entry inserted successfully'
        ], 200);

    }

    /**
     * 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)
    {
        //
    }
}
