<?php

namespace App\Http\Controllers;

use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\WorkGroupMaster;
use Illuminate\Http\Request;
use Str;

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

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

    /**
     * Display the all available resource.
     */
    public function get_all_data(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()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 403);
        }

        $machines = Machine::with('plant')->with('workGroupMaster')->orderBy('plant_id')->get();
        $machinesData = $machines->map(function ($machine) {
            return [
                'plant_code' => $machine->plant ? (string) $machine->plant->code : '',
                'group_work_center' => $machine->workGroupMaster ? (string) $machine->workGroupMaster->name : '',
                'work_center' => $machine->work_center ?? '',
            ];
        });

        return response()->json([
            'machines' => $machinesData,
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function get_data(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()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 403);
        }

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

        if ($plantCode == null || $plantCode == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || ! is_numeric($plantCode) || ! preg_match('/^[1-9]\d{3,}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid plant code found!',
            ], 400);
        } elseif ($lineName == null || $lineName == '' || Str::length($lineName) <= 0) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line name can't be empty!",
            ], 400);
        }

        $plant = Plant::where('code', $plantCode)->first();
        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant Code '{$plantCode}' not found!",
            ], 400);
        }

        $plantId = $plant->id;

        $line = Line::where('name', $lineName)->first();
        if (! $line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line Name '{$lineName}' not found!",
            ], 400);
        }

        $line = Line::where('name', $lineName)->where('plant_id', $plantId)->first();
        if (! $line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line Name '{$lineName}' not found for the plant!",
            ], 400);
        }

        $lineId = $line->id; // no_of_operation
        $lineWorkGroup1Id = $line->work_group1_id;
        $lineWorkGroup2Id = $line->work_group2_id;
        if ($line->no_of_operation == null || $line->no_of_operation == '' || $line->no_of_operation == 0 || ! is_numeric($line->no_of_operation)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Group work center not found for the plant & line!',
            ], 400);
        }

        $test = [];
        $lineWorkGroupIds = [];
        for ($i = 1; $i <= $line->no_of_operation; $i++) {
            $curWorkGroupId = $line->{"work_group{$i}_id"};
            if (in_array($curWorkGroupId, $lineWorkGroupIds)) {
                continue;
            } else {
                $lineWorkGroupIds[] = $curWorkGroupId;
            }

            $test[] = [
                'group_work_center' => WorkGroupMaster::where('id', $curWorkGroupId)->first()->name ?? '',
                'operation_number' => WorkGroupMaster::where('id', $curWorkGroupId)->first()->operation_number ?? '',
                'work_centers' => Machine::where('plant_id', $plantId)->where('work_group_master_id', $curWorkGroupId)->orderBy('work_center')->pluck('work_center')->toArray() ?? [],
            ];
        }

        if ($lineWorkGroupIds) {
            return response()->json([
                'machines' => $test,
            ]);
        }
        // $machines = Machine::with('plant')->with('workGroupMaster')->orderBy('plant_id')->get();
        // $machinesData = $machines->map(function($machine) use ($lineId, $plantId) {
        //     $test = [];
        //     for ($i = 1; $i <= 10; $i++) {
        //         $workGroupName = $this->data["work_group{$i}_id"] ?? null;
        //         if (!$workGroupName) {
        //             continue;
        //         }

        //         $workGroupRecord = WorkGroupMaster::where('name', $workGroupName)
        //             ->where('plant_id', $plant->id)
        //             ->first();

        //         $existsInLines = Line::where('plant_id', $plantId)
        //             ->where('i', '!=', $lineId)
        //             ->where("work_group{$i}_id", $workGroupRecord->id)
        //             ->first();

        //         $test[] = $existsInLines;

        //         if ($existsInLines) {
        //             $warnMsg[] = "Work group '{$workGroupName}' is already assigned to another line in plant '{$this->data['plant']}'";
        //         }

        //         $this->data["work_group{$i}_id"] = $workGroupRecord->id;
        //     }
        //     return $test[];
        // });
        // return response()->json([
        //     'machines' => $machinesData
        // ]);
    }

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

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