<?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'];
//    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;

        if($this->one_time_use) {
            $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->target_all_customers) {
                return !$redeemed;
            }
            $result = DB::select("select 1 from PromotionCustomerTrigger_Customer where promotioncustomertrigger_id = ? and customer_id = ? and deleted_at = 0", [$this->id, $soldToCustomer->id]);
            if (count($result) > 0) {
                return !$redeemed;
            } else {
                return false;
            }
        } else {
            if ($this->target_all_customers) {
                return true;
            } else {
                    $result = DB::select("select 1 from PromotionCustomerTrigger_Customer where promotioncustomertrigger_id = ? and customer_id = ? and deleted_at = 0", [$this->id, $soldToCustomer->id]);
                    if (count($result) > 0) {
                        return true;
                    } else {
                        return false;
                    }
            }

        }
        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();
            }
        });
    }
}