<?php

namespace App\Repositories;

use App\Services\Util;
use App\Models\PromotionUser;
use App\Models\PromotionAdmin;
use App\Models\PromotionUserProduct;
use Illuminate\Support\Facades\Auth;
use App\Models\PromotionAdminProduct;

class UserPromotionRepository extends BaseRepository {


    public function __construct(PromotionUser $model){

        $this->model = $model;
    }

    public function update($id, $data)
    {

        $data['active'] = isset($data['active']) ? 1 : 0;
        $data['pick_up'] = isset($data['pick_up']) ? 1 : 0;
        $data['url'] = Util::sanitize($data['user_promotion_url'], true, false, true, true);
        
        $this->model = $this->getById($id);
        $this->model->fill($data);
        $this->model->save();

        $this->updateProducts($id, $data);
        return $this->model;
    }
    
    public function updateProducts($id, $data){

        $this->model = $this->getById($id);
        if(isset($data['products_qty'])){
            foreach($data['products_qty'] as $pa_id => $qty){
                $PromotionAdminProduct = PromotionAdminProduct::findOrFail($pa_id);
                $PromotionUserProduct = $PromotionAdminProduct->getPromotionUserProducts($this->model);

                if(isset($data['products_user'][$pa_id]) && $data['products_user'][$pa_id] > 0 && $PromotionUserProduct){
                    $PromotionUserProduct->fill([
                        'open_items' => intval($qty),
                        'active' => isset($data['products_active'][$pa_id]) ? 1 : 0,
                    ]);
                    $PromotionUserProduct->save();
                }else{
                    $user_product = PromotionUserProduct::create([
                        'promotion_admin_id' => $PromotionAdminProduct->promotion_admin_id,
                        'promotion_user_id' => $this->model->id,
                        'promotion_admin_product_id' => $PromotionAdminProduct->id,
                        'product_id' => $PromotionAdminProduct->product_id,
                        'open_items' => intval($qty),
                        'active' => isset($data['products_active'][$pa_id]) ? 1 : 0,

                    ]);
                }
            }
        }
        
        return $this->model;
    }
    
    public function create($data){

        if(isset($data['promotion_admin_id'])){
            $PromotionAdmin = PromotionAdmin::findOrFail($data['promotion_admin_id']);
    
            $this->model = PromotionUser::create([
                'promotion_admin_id' => $PromotionAdmin->id,
		        'user_id' => Auth::user()->id,
                'user_address' => Auth::user()->getFullAddress()
            ]);
            return $this->model;
        }
        return false;

    }


}