<?php

namespace App\Http\Controllers;

use App\Models\AmbitsEquipment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use Yajra\DataTables\Facades\DataTables;

use App\Models\Equipment;
use App\Models\Plant;
use App\Models\CompanyProject;
use App\Models\User;


use App\Models\ConstructionWorkstation;
use App\Models\EquipmentType;
use Mockery\Undefined;

class ProjectoDatacontroller extends Controller
{
    public function receivePlants($clientId){
        if($clientId == 'all'){
            $allPlants = Plant::all();
            return response()->json($allPlants);
        }
        dd($clientId);

    }


    public function getEquipmentDetails($receiveListEquipmentId)
    {
        $ids = explode(',', $receiveListEquipmentId);

        $equipments = Equipment::whereIn('equipment_id', $ids)->get();

        // Pegar os unique "equipment_type_id"s
        $equipmentTypeIds = $equipments->pluck('equipment_type_id')->unique();

        // Obter todos os "AmbitsEquipment" para esses "equipment_type_id"s
        $ambitsEquipments = AmbitsEquipment::whereIn('equipment_type_id', $equipmentTypeIds)->get();

        // Mapear os "AmbitsEquipment" de volta aos equipamentos correspondentes
        foreach ($equipments as $equipment) {
            $equipment->ambits = $ambitsEquipments->where('equipment_type_id', $equipment->equipment_type_id);
        }
        return response()->json($equipments);
    }


    public function receiveAllInstallationEquipment($receiveNumberProject)
    {

        $receveProject = CompanyProject::find($receiveNumberProject);
        $receveEquipments = Equipment::whereHas('unit.plant', function ($query) use ($receveProject) {
            $query->where('plants.plant_id', '=', $receveProject->plant_id);
        })
            ->where('company_projects_id', null)  // Adiciona a condição aqui
            ->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment'])
            ->get();


        return DataTables::of($receveEquipments)
            ->addColumn('equipment_type', function ($row) {
                return $row->equipmentType->equipment_type_name;
            })
            ->addColumn('unit', function ($row) {
                return $row->unit->unit_name;
            })
            ->toJson();
    }


    public function HomePage()
    {
        $CompanyProject = CompanyProject::all();

        return view('Admin/index')
            //  return view('codePronto');
            ->with("CompanyProject", $CompanyProject);
    }

    public function ManageAssets()
    {

        $units = DB::table('plants')
            ->join('units', 'plants.plant_id', '=', 'units.plant_id')
            ->join('users', 'plants.user_id', '=', 'users.user_id')
            ->select('plants.*', 'units.unit_name', 'users.user_name as user_name')
            ->get();
        $equipments = Equipment::all();
        // $equipaments = DB::table('equipaments')
        //     ->join('factories','equipaments.factory_id', '=', 'factories.factories_id')
        //     ->join('equipament_types', 'equipaments.equipament_type_id', '=' , 'equipament_types.equipament_type_id')
        //     ->select('equipaments.*', 'factories.factories_name', 'equipament_types.equipment_type_name')
        //     ->get();

        $allEquipmentType = EquipmentType::all();
        $allClients = User::where('type_users', 3)->get();

        return view('Admin/DataManagement/manageassets', compact('units', 'equipments','allEquipmentType','allClients'));
    }

    public function showUnit($id)
    {

        $equipaments = Equipment::where('equipment_id', $id)->firstOrFail();
        return view('Admin/DataManagement/showEquipament', compact('equipaments'));
    }

    



    public function receiveEquipmentsProject($receiveNumberProject)
    {
        // Recebe os dados vindos da funcao 'data' criada na view 
        $equipment_type_id = request('equipment_type_id');
        $ambits_id = request('ambits_id');

        //Recebe sempre apenas os equipamentos relacionados a obra
        // $model = Equipment::where('company_projects_id', $receiveNumberProject);

        // Caso 'equipment_type_id' seja '#', mostra todos os equipamentos
        if ($equipment_type_id == '#') {
            $model = Equipment::query()
                ->where('company_projects_id', $receiveNumberProject)
                ->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment']);
        }
        // Caso 'equipment_type_id' não seja '#', filtra os equipamentos por tipo e Âmbito (caso 'ambits_id' não seja '#')
        else {
            $equipment_type_id = intval($equipment_type_id);
            $model = Equipment::where('equipments.equipment_type_id', $equipment_type_id)
                ->where('company_projects_id', $receiveNumberProject)
                ->join('equipment_association_ambits', 'equipments.equipment_id', '=', 'equipment_association_ambits.equipment_id')
                ->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment']);

            if ($ambits_id != '#') {
                $ambits_id = intval($ambits_id);
                $model->where('equipment_association_ambits.ambits_id', $ambits_id)
                    ->where('company_projects_id', $receiveNumberProject);
            }
        }
        return DataTables::of($model)
            ->addColumn('equipment_type', function ($row) {
                return $row->equipmentType->equipment_type_name;
            })
            ->addColumn('Unit', function ($row) {
                return $row->unit->unit_name;
            })
            ->addColumn('Ambits', function ($row) {
                return $row->equipmentAssociationAmbit->ambitsEquipment->ambits_description;
            })
            ->addColumn('order_tasks', function ($row) {
                return $row->orderEquipmentTasks->map(function ($task) {
                    return $task->elementalTask->elemental_tasks_code;
                })->implode(' ||');
            })
            ->addColumn('current_task', function ($row) {
                return $row->controlEquipmentWorkstation->map(function ($task) {
                    return $task->elementalTask->elemental_tasks_code;
                })->implode(' ||');
            })
            ->addColumn('Inspec', function ($row) {
                return $row->hasInspectionYes() ? 'Sim' : 'Nao';
            })
            ->toJson();
    }

    public function receiveAllEquipments()
    {
        $model = Equipment::all();
        // ->with(['equipmentType', 'unit']);


        return DataTables::of($model)
            // ->addColumn('equipment_type', function ($row) {
            //     return $row->equipmentType->equipment_type_name;
            // })
            // ->addColumn('Unit', function ($row) {
            //     return $row->unit->unit_name;
            // })
            ->toJson();
    }

    public function receiveWorkstationProject($receiveNumberProject)
    {
        $model = ConstructionWorkstation::where('company_projects_id', $receiveNumberProject)->with('workstationsAssociationTasks');

        return DataTables::of($model)
            ->addColumn('workstations_Association_Tasks', function ($row) {
                return $row->workstationsAssociationTasks->map(function ($task) {
                    return $task->elementalTask->elemental_tasks_code;
                })->implode(' ||');
            })

            ->toJson();
    }
}
