<?php

namespace App\Livewire;

use App\Models\CheckPointTime;
use App\Models\GuardPatrolEntry;
use Carbon\Carbon;
use Livewire\Component;

class GuardPatrolEntryDataTable extends Component
{
    // public $plantId;
    // public $date;

    public $newNameFound;
    public $guardName;
    public $checkPointName;
    public $startTime;
    public $endTime;
    public $start;
    public $finish;
    public $begin;
    public $end;
    public $labTime;
    public $minDiff;
    public $seqNoCnt = 0;
    public $seqNo = 0;
    public $isSequenced = true;
    public $sequences = [];
    public $seqTime;
    public $seqTimes = [];
    public $startSeqCheckPoints = [];
    public $records = [];

    protected $listeners = [
        'loadGuardData' => 'loadGuardPatrolData',
    ];

    public function loadGuardPatrolData($plantId, $date)
    {
        // $this->plantId = $plantId;
        // $this->date = $date;

        $this->records = [];
        $this->newNameFound = true;
        $this->guardName = null;
        $this->checkPointName = null;
        $this->startTime = null;
        $this->endTime = null;
        $this->start = null;
        $this->finish = null;
        $this->begin = null;
        $this->end = null;
        $this->labTime = null;
        $this->minDiff = 0;
        $this->seqNoCnt = 0;
        $this->seqNo = 0;
        $this->isSequenced = true;
        $this->sequences = [];
        $this->seqTime = null;
        $this->seqTimes = [];
        $this->startSeqCheckPoints = [];

        if (!$plantId || !$date)
        {
            $this->records = [];
            return;
        }

        $this->seqNoCnt = CheckPointTime::where('plant_id', $plantId)->count('sequence_number');

        for ($i = 1; $i <= $this->seqNoCnt; $i++) {
            $this->startSeqCheckPoints[$i] = CheckPointTime::with('checkPointNames1')->with('checkPointNames2')->where('sequence_number', $i)->where('plant_id', $plantId)->first();
        }

        $this->sequences = array_fill(1, $this->seqNoCnt, "X");
        $this->seqTimes = array_fill(1, $this->seqNoCnt, null);

        $hasSingleGuard = GuardPatrolEntry::whereDate('patrol_time', $date)->where('plant_id', $plantId)->orderBy('patrol_time', 'asc')->get();

        $checking = 0;
        $records = GuardPatrolEntry::with('guardNames')->with('checkPointNames')->whereDate('patrol_time', $date)->where('plant_id', $plantId)->orderBy('patrol_time', 'asc')->get(); //desc Carbon::parse($record->patrol_time)->toTimeString()
        foreach ($records as $index => $record) { //foreach ($startSeqCheckPoints as $seq => $checkpoint)
            $checking++;
            $guardName = $record->guardNames ? $record->guardNames->name : null;
            $checkPointName = $record->checkPointNames ? $record->checkPointNames->name : null;
            if ($this->guardName != $guardName || $this->newNameFound) {//if ($this->newNameFound) {
                if ($this->guardName)
                {
                    $recordData = [
                        'guard_name' => $this->guardName,
                        'start_time' => $this->startTime,
                        'end_time' => $this->endTime,
                        'lap_time' => $this->labTime,
                    ];

                    for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                        $recordData["Sequence_$i"] = $this->sequences[$i];
                        $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                    }

                    $this->records[] = $recordData;
                }

                $this->seqTimes = array_fill(1, $this->seqNoCnt, null);

                $this->guardName = $guardName;
                $this->startTime = Carbon::parse($record->patrol_time)->toTimeString(); //"2025-06-01 00:07:12"
                $this->start = Carbon::parse($record->patrol_time);
                $this->endTime = Carbon::parse($record->patrol_time)->toTimeString(); //"2025-06-01 00:07:12"
                $this->finish = Carbon::parse($record->patrol_time);
                $this->begin = Carbon::parse($record->patrol_time);
                $this->end = Carbon::parse($record->patrol_time);
                $this->labTime = (int)$this->start->diffInMinutes($this->finish);
                $this->minDiff = (int)$this->begin->diffInMinutes($this->end);
                $this->seqTime = $this->begin->toTimeString(). "  -  " . $this->end->toTimeString();
                $this->seqNo = 0;
                $this->newNameFound = false;
                $this->isSequenced = true;
            }
            else if ($this->guardName == $guardName && $this->start && $this->begin)
            {
                $this->endTime = Carbon::parse($record->patrol_time)->toTimeString(); //"2025-06-01 00:07:12"
                $this->finish = Carbon::parse($record->patrol_time);
                $this->end = Carbon::parse($record->patrol_time);
                $this->labTime = (int)$this->start->diffInMinutes($this->finish);
                $this->minDiff = (int)$this->begin->diffInMinutes($this->end);
                $this->seqTime = $this->begin->toTimeString(). "  -  " . $this->end->toTimeString();
                $this->begin = Carbon::parse($record->patrol_time);
                // $this->seqNo = 0;
            }

            $this->seqNo++;

            if ($this->seqNo == 1) {
                if ($checkPointName == $this->startSeqCheckPoints[$this->seqNo]->checkPointNames1->name) {//"STP BACKSIDE"
                    $this->isSequenced = true;
                    $this->sequences = array_fill(1, $this->seqNoCnt, "X");
                }
                else {
                    $this->isSequenced = false;
                    $this->sequences = array_fill(1, $this->seqNoCnt, "X");
                }

                if (($index+1) == count($hasSingleGuard))
                {
                    if ($this->guardName)
                    {
                        $recordData = [
                            'guard_name' => $this->guardName,
                            'start_time' => $this->startTime,
                            'end_time' => $this->endTime,
                            'lap_time' => $this->labTime,
                        ];

                        for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                            $recordData["Sequence_$i"] = $this->sequences[$i];
                            $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                        }

                        $this->records[] = $recordData;
                    }
                }
            }
            else if ($this->seqNo >= ($this->seqNoCnt+1)) {
                $this->seqTimes[$this->seqNo-1] = $this->seqTime;
                if ($checkPointName == $this->startSeqCheckPoints[$this->seqNo-1]->checkPointNames2->name) {//"D 72 END"
                    if ($this->isSequenced) {
                        $this->sequences[$this->seqNo-1] = $this->minDiff;
                    }
                }
                else {
                    $this->isSequenced = false;
                }
                $this->newNameFound = true;

                if ($hasSingleGuard->unique('guard_name_id')->count() == 1)
                {
                    if (($this->seqNoCnt+1) == count($hasSingleGuard))
                    {
                        //dd("Has 1 Guard and single patrol round (".($this->seqNoCnt+1).") is present");
                        if ($this->guardName)
                        {
                            $recordData = [
                                'guard_name' => $this->guardName,
                                'start_time' => $this->startTime,
                                'end_time' => $this->endTime,
                                'lap_time' => $this->labTime,
                            ];

                            for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                                $recordData["Sequence_$i"] = $this->sequences[$i];
                                $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                            }

                            $this->records[] = $recordData;
                        }
                    }
                    else if (($index+1) == count($hasSingleGuard))
                    {
                        if ($this->guardName)
                        {
                            $recordData = [
                                'guard_name' => $this->guardName,
                                'start_time' => $this->startTime,
                                'end_time' => $this->endTime,
                                'lap_time' => $this->labTime,
                            ];

                            for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                                $recordData["Sequence_$i"] = $this->sequences[$i];
                                $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                            }

                            $this->records[] = $recordData;
                        }
                    }
                }
                else if (($index+1) == count($hasSingleGuard))
                {
                    if ($this->guardName)
                    {
                        $recordData = [
                            'guard_name' => $this->guardName,
                            'start_time' => $this->startTime,
                            'end_time' => $this->endTime,
                            'lap_time' => $this->labTime,
                        ];

                        for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                            $recordData["Sequence_$i"] = $this->sequences[$i];
                            $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                        }

                        $this->records[] = $recordData;
                    }
                }
            }
            else // if ($this->seqNo >= 2) {
            {
                $this->seqTimes[$this->seqNo-1] = $this->seqTime;
                if ($checkPointName == $this->startSeqCheckPoints[$this->seqNo]->checkPointNames1->name) {//"CANTEEN"
                    if ($this->isSequenced) {
                        $this->sequences[$this->seqNo-1] = $this->minDiff;
                    }
                }
                else {
                    $this->isSequenced = false;
                }

                if ($hasSingleGuard->unique('guard_name_id')->count() == 1)
                {
                    if ($this->seqNo == count($hasSingleGuard))
                    {
                        //dd("Has 1 Guard and single patrol round (".($this->seqNoCnt+1).") is present");
                        if ($this->guardName)
                        {
                            $recordData = [
                                'guard_name' => $this->guardName,
                                'start_time' => $this->startTime,
                                'end_time' => $this->endTime,
                                'lap_time' => $this->labTime,
                            ];

                            for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                                $recordData["Sequence_$i"] = $this->sequences[$i];
                                $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                            }

                            $this->records[] = $recordData;
                        }
                    }
                    else if (($index+1) == count($hasSingleGuard))
                    {
                        if ($this->guardName)
                        {
                            $recordData = [
                                'guard_name' => $this->guardName,
                                'start_time' => $this->startTime,
                                'end_time' => $this->endTime,
                                'lap_time' => $this->labTime,
                            ];

                            for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                                $recordData["Sequence_$i"] = $this->sequences[$i];
                                $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                            }

                            $this->records[] = $recordData;
                        }
                    }
                }
                else if (($index+1) == count($hasSingleGuard))
                {
                    if ($this->guardName)
                    {
                        $recordData = [
                            'guard_name' => $this->guardName,
                            'start_time' => $this->startTime,
                            'end_time' => $this->endTime,
                            'lap_time' => $this->labTime,
                        ];

                        for ($i = 1; $i <= $this->seqNoCnt; $i++) {
                            $recordData["Sequence_$i"] = $this->sequences[$i];
                            $recordData["Sequence_Time_$i"] = $this->seqTimes[$i];
                        }

                        $this->records[] = $recordData;
                    }
                }
            }
        }
    }

    public function render()
    {
        return view('livewire.guard-patrol-entry-data-table');
    }
}
