<?php

namespace App\Repositories\Opportunity;

use App\Models\Opportunity;
use App\Enums\StagesOpportunity;

class OpportunityRepository implements OpportunityRepositoryInterface
{
    public function query(){
        return Opportunity::query();
    }
    public function getAllOpportunities(){
        return Opportunity::all();
    }
    public function getAllOportunitiesForUser($userId){
        return Opportunity::where('user_id',$userId)->orderBy('updated_at', 'desc')->get();
    }
    public function getOpportunityById($id){
        return Opportunity::find($id);
    }
    public function createOpportunity($customer,$data){
        return Opportunity::create([
            'start_date' => now(),
            'customer_id' => $customer->id,
            'description' => $data['description'] ?? null,
            'stage_id' => $data['stage_id'] ?? StagesOpportunity::LEAD->value(),
            'user_id' => $data['user_id'] ?? null,
            'source_id' => $data['source_id'] ?? null,
            'contact_method_id' => $data['contact_method_id'] ?? null,
            'customer_references_id' => $data['customer_references_id'] ?? null,
            'property_id' => $data['property_id'] ?? null,
        ]);
    }
    public function updateOpportunity($id, $data){
        $opportunity = Opportunity::find($id);
        $opportunity->update($data);
        return $opportunity;
    }
    public function deleteOpportunity($id){

    }
    public function getActiveOpportunityForCustomer($customerId){
        return Opportunity::where('customer_id', $customerId)
        ->whereNotNull('end_state')
        ->first();
    }
    public function convertOpportunityToProspect($opportunityId, $data) {
        $opportunity = Opportunity::find($opportunityId);
        $opportunity->update([
            'stage_id' => StagesOpportunity::PROSPECT->value(),
        ]);
        return $opportunity;
    }

    public function changeStage($opportunityId, $stage_id) {
        $opportunity = Opportunity::find($opportunityId);
        $opportunity->update([
            'stage_id' => $stage_id,
        ]);
        return $opportunity;
    }

    public function isProspectOpportunity($opportunityId){
        $opportunity = Opportunity::find($opportunityId);
        return $opportunity->stage_id == StagesOpportunity::PROSPECT->value();
    }
}
