<?php

namespace App\Http\Livewire\Workflow;

use App\Models\Location;
use App\Models\Stage;
use App\Models\Stock_take;
use App\Models\Stock_take_material;
use App\Models\Workflow_comment;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class PlantLevel extends Component
{
    public $stocks = [];
    public $locations = [];
    public $listMode = true;
    public $viewMode = false;
    public $materials = [];
    public $location;
    public $location_code, $comment;
    public $my_comment;
    public $other_comments;

    public function fetch()
    {
        $user = Auth::user();
        return Stock_take_material::groupBY('material_type')
            ->with('stock_takes')
            ->whereRelation('stock_takes', 'status', 'active')
            ->whereRelation('stock_takes', 'plant_code', $user->plant_code)
            ->select('material_type', DB::raw('sum(current_stock) as total_current'), DB::raw('sum(sap_stock) as total_sap'))
            ->with(['types'])
            ->get();
    }

    public function fetch_locations()
    {
        $user = Auth::user();
        return Stock_take::where([['plant_code', $user->plant_code], ['status', 'active']])->whereNotNull('doc_no')->with(['locations'])->get();
    }

    public function view_locations($plant_code)
    {
    }

    public function fetch_my_comment()
    {
        $user = Auth::user();
        if ($user->hasRole('Plant Accountant')) {
            return Stage::where([['plant_code', $user->plant_code], ['status', 'active']])
                ->with('comments', function ($q) {
                    $q->where('role', 'plant_accountant');
                })
                ->latest()->first();
        } elseif ($user->hasRole('Plant Controller')) {
            return Stage::where([['plant_code', $user->plant_code], ['status', 'active']])
                ->with('comments', function ($q) {
                    $q->where('role', 'plant_controller');
                })
                ->latest()->first();
        } elseif ($user->hasRole('Plant Manager')) {
            return Stage::where([['plant_code', $user->plant_code], ['status', 'active']])
                ->with('comments', function ($q) {
                    $q->where('role', 'plant_manager');
                })
                ->latest()->first();
        }
    }

    public function view_location_stocks()
    {
        try {
            $this->listMode = false;
            $this->viewMode = true;
            if (!$this->location_code) {
                $this->materials = [];
                session()->flash('danger', 'Please select location');
            } else {
                $this->location = Location::where('storage_location_code', $this->location_code)->first();
                $stock_take = Stock_take::where([['storage_location_code', $this->location_code], ['status', 'active']])->first();
                $this->materials = Stock_take_material::where('stock_take_id', $stock_take->id)->with(['materials', 'comments'])->get();
            }
        } catch (\Throwable $th) {
            session()->flash('danger', $th->getMessage());
        }
    }

    public function fetch_other_comments()
    {
        $user = Auth::user();
        if ($user->hasRole('Plant Controller')) {
            return Stage::where([['plant_code', $user->plant_code], ['status', 'active']])
                ->with('comments', function ($q) {
                    $q->where('role', '!=', 'plant_controller');
                })
                ->latest()->first();
        } elseif ($user->hasRole('Plant Manager')) {
            return Stage::where([['plant_code', $user->plant_code], ['status', 'active']])
                ->with('comments', function ($q) {
                    $q->where('role', '!=', 'plant_manager');
                })
                ->latest()->first();
        } elseif ($user->hasRole('Plant Accountant')) {
            return Stage::where([['plant_code', $user->plant_code], ['status', 'active']])
                ->with('comments', function ($q) {
                    $q->where('role', '!=', 'plant_accountant');
                })
                ->latest()->first();
        }
    }

    public function store_comment()
    {
        try {
            $user = Auth::user();
            $stage = Stage::where([['plant_code', $user->plant_code], ['status', 'active']])->latest()->first();

            if ($stage) {
                $data = [
                    'stage_id' => $stage->id,
                    'user_id' => $user->id,
                    'comment' => $this->comment,
                ];
                $check = Workflow_comment::where([['user_id', $user->id], ['stage_id', $stage->id]])->first();
                if ($user->hasRole('Plant Accountant')) {
                    if ($check) {
                        $check->update(array_merge($data));
                    } else {
                        Workflow_comment::create(array_merge($data, ['role' => 'plant_accountant']));
                        $stage->update(['level' => 'Plant Controller']);
                    }
                } elseif ($user->hasRole('Plant Controller')) {
                    if ($check) {
                        $check->update(array_merge($data));
                    } else {
                        Workflow_comment::create(array_merge($data, ['role' => 'plant_controller']));
                        $stage->update(['level' => 'Plant Manager']);
                    }
                } elseif ($user->hasRole('Plant Manager')) {
                    if ($check) {
                        $check->update(array_merge($data));
                    } else {
                        Workflow_comment::create(array_merge($data, ['role' => 'plant_manager']));
                        $stage->update(['level' => 'Inventory Accountant']);
                    }
                }
                $this->reset();
                session()->flash('success', 'Comment added successfully!');
            } else {
                session()->flash('danger', 'This workflow is still in the storage clerk stage');
            }
        } catch (\Throwable $th) {
            session()->flash('danger', $th->getMessage());
        }
    }

    public function edit($id)
    {
        $comm = Workflow_comment::where('id', $id)->first();
        $this->comment = $comm->comment;
    }
    public function render()
    {
        sleep(seconds: 3);
        $user = Auth::user();
        $this->stocks = $this->fetch();
        $this->locations = $this->fetch_locations();
        // dd($this->locations);
        $this->my_comment = $this->fetch_my_comment();
        if ($user->hasRole('Plant Controller|Plant Manager|Plant Accountant')) {
            $this->other_comments = $this->fetch_other_comments();
        }
        return view('livewire.workflow.plant-level');
    }
}
