<?php

namespace App\Repositories\Procedure;

use App\Models\Opportunity;
use App\Models\OpportunityProcedure;
use App\Models\Procedure;

class ProcedureOpportunityRepository implements ProcedureOpportunityRepositoryInterface
{
    public function create(array $data)
    {
        return OpportunityProcedure::create($data);
    }
    public function createByStage($stage_id, $opportunity_id)
    {
        $procedures = Procedure::where('stage_id', $stage_id)->get();

        foreach ($procedures as $procedure) {
            OpportunityProcedure::create([
                'procedure_id' => $procedure->id,
                'opportunity_id' => $opportunity_id,
                'is_check' => false,
            ]);
        }
    }
    public function find($opportunity_id, $procedure_id)
    {
        return OpportunityProcedure::where('opportunity_id', $opportunity_id)->where('procedure_id', $procedure_id)->first();
    }
    public function findbyProcedure($procedure_id)
    {
        return OpportunityProcedure::where('procedure_id', $procedure_id)->first();
    }
    public function findbyOpportunity($opportunity_id)
    {
        return OpportunityProcedure::where('opportunity_id', $opportunity_id)->first();
    }
    public function update($opportunity_id, $procedure_id, $data)
    {
        return OpportunityProcedure::where('opportunity_id', $opportunity_id)
            ->where('procedure_id', $procedure_id)
            ->update($data);
    }
    public function delete($opportunity_id, $procedure_id)
    {
        return OpportunityProcedure::where('opportunity_id', $opportunity_id)->andwhere('procedure_id', $procedure_id)->delete();
    }
    public function all()
    {
        return OpportunityProcedure::all();
    }
    public function allquery()
    {
        return OpportunityProcedure::query();
    }
    public function restore($id)
    {
        return OpportunityProcedure::withTrashed()->find($id)->restore();
    }

    public function findbyOpportunityStage($opportunity_id, $stage_id)
    {
        return Opportunity::find($opportunity_id)
            ->procedures()
            ->where('procedures.stage_id', $stage_id) // Filtrar por el estado 2
            ->withPivot('is_check') // Incluir el campo 'is_check' desde la tabla pivote
            ->get();
    }

    public function verifOpportunitybyStage($opportunity_id, $stage_id)
    {
        $opportunity = Opportunity::find($opportunity_id);
        $procedures = $opportunity->procedures()
            ->where('procedures.stage_id', $stage_id)
            ->withPivot('is_check')
            ->get();
        $allChecked = $procedures->every(function ($procedure) {
            return $procedure->pivot->is_check == true;
        });
        return $allChecked;
    }
}
