<?php

namespace Hilco\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use LogicException;

class PromotionCustomerTrigger extends PromotionTriggerDetails {
    protected $table = 'PromotionCustomerTriggers';
    protected $fillable = ['target_all_customers', 'one_time_use', 'commit_sequence'];
//    protected $with = ['customers'];

    /**
     * @return BelongsToMany
     */
    public function customers() {
        return $this->belongsToMany(Customer::class, 'PromotionCustomerTrigger_Customer', 'promotioncustomertrigger_id', 'customer_id')
                    ->wherePivot('deleted_at', '=', DB::raw(0))
                    ->withPivot(['excluded', 'temporary_email', 'redeemed'])
            ;
    }

    public function promotionCustomerTriggerCustomers() {
        return $this->hasMany(PromotionCustomerTrigger_Customer::class, 'promotioncustomertrigger_id', 'id');
    }

    public function isTriggered(Customer $soldToCustomer, $webCartItems, $distinctPartInfo = []) {
        $promotionId = $this->trigger->promotion_id;
        $redeemed =
            $soldToCustomer->orders()->whereRaw(
                "SalesOrders.order_status NOT IN ('DENIED','DISCARDED','CANCELLED','CANCELED','UNSUBMITTED') 
                AND EXISTS (
                    SELECT 1 
                    FROM Promotion_SalesOrder 
                    WHERE SalesOrders.id = Promotion_SalesOrder.salesorder_id 
                    AND Promotion_SalesOrder.promotion_id = ? 
                    AND Promotion_SalesOrder.deleted_at = 0
                )",
                [$promotionId])->count() > 0;

        if($this->one_time_use) {
            $customer = $this->customers->where('id', '=', $soldToCustomer->id)->first();
            if (isset($customer)) {
                return !$redeemed;
            } else {
                if ($this->target_all_customers) {
                    return !$redeemed;
                }
            }
        } else {
            if ($this->target_all_customers) {
                return true;
            } else {
                $customer = $this->customers->where('id', '=', $soldToCustomer->id)->first();
            }
        }
        return !is_null($customer);
    }

    public function postTriggerOperation($soldToCustomer) {
        $this->customers()->updateExistingPivot($soldToCustomer->id, ['redeemed' => 1]);
    }

    public static function boot() {
        parent::boot();

        static::deleted(function (PromotionCustomerTrigger $promotionCustomerTrigger) {
            $promotionCustomerTriggerCustomers =
                PromotionCustomerTrigger_Customer::where('promotioncustomertrigger_id', '=', $promotionCustomerTrigger->id)->get();
            foreach ($promotionCustomerTriggerCustomers as $promotionCustomerTriggerCustomer) {
                $promotionCustomerTriggerCustomer->delete();
            }
        });
    }
}