<?php

namespace App\Http\Livewire\Workflow;

use App\Http\Controllers\Helpers\HelperController;
use App\Models\People;
use App\Models\Stock_take;
use App\Models\Stock_take_material;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class LocationLevel extends Component
{
    public $locations = [];
    public $stock_take_id;
    public $comment;
    public $materials = [];
    public $material;
    public $material_id;

    public function fetch_locations()
    {
        $user = Auth::user();
        $assigned_locations = People::where('user_id', $user->id)->whereNotNull('location_code')->get();
        $locs = [];
        foreach ($assigned_locations as $key => $loc) {
            $get_stock = Stock_take::where([['storage_location_code', $loc->location_code], ['status', 'active']])->whereNotNull('doc_no')->with('locations')->first();
            if ($get_stock) {
                $locs[] = $get_stock;
            }
        }
        return $locs;
    }

    public function location_change()
    {
        $mats = Stock_take_material::where('stock_take_id', $this->stock_take_id)->get();
        return $mats;
    }

    public function save_comment()
    {
        $mat = Stock_take_material::where('id', $this->material_id)->first();
        $mat->update(['comment' => $this->comment]);
        //check if all materials have comments and close
        $check = Stock_take_material::where('stock_take_id', $this->stock_take_id)->whereNull('comment')->get();
        if (count($check) == 0) {
            Stock_take::findOrFail($this->stock_take_id)->update(['clerk_approval' => 'approved']);
        }
        // autorun stage flow if all have been approved by clerk
        HelperController::start_stage_flow();
        session()->flash('danger', 'Comment added successfully!');
    }

    public function add_comment($id)
    {
        $this->material = Stock_take_material::where('id', $id)->first();
        $this->material_id = $this->material->id;
        $this->comment = $this->material->comment;
    }
    public function render()
    {
        $this->locations = $this->fetch_locations();
        if (!is_null($this->stock_take_id)) {
            $this->materials = $this->location_change();
        }
        return view('livewire.workflow.location-level');
    }
}