<?php

namespace App\Http\Livewire;

use App\Models\Eklentiler;
use App\Models\Kuponcode;
use Livewire\Component;
use Cart;

class Sepet extends Component


{

    protected $listeners = ['refreshComponent'=>'$refresh'];


    public $name;
    public $deger;


    public function destroy($id){
        Cart::remove($id);
        $this->emitTo('sepeticonu','refreshComponent');

        session()->flash('success','Sepeten Başarıyla Silindi');


    }

    public function increasequantity($rowId){
        $product=Cart::get($rowId);
        $qty=$product->qty + 1;
        Cart::update($rowId,$qty);
        $this->emitTo('sepeticonu','refreshComponent');

    }

    public function descreasequantity($rowId){
        $product=Cart::get($rowId);
        $qty=$product->qty - 1;
        Cart::update($rowId,$qty);
        $this->emitTo('sepeticonu','refreshComponent');


    }




    public function render()
    {
        $eklentiler=Eklentiler::where('durum',1)->where('sepettegoster',1)->get();

        return view('livewire.sepet',compact('eklentiler'));
    }



    public function addpaket($product_id,$product_baslik,$product_fiyat)
    {
        Cart::add($product_id,$product_baslik,1,$product_fiyat)->associate('\App\Models\Eklentiler');
        $this->emitTo('sepet','refreshComponent');
        $this->emitTo('sepeticonu','refreshComponent');
        $this->emitTo('iskonto','refreshComponent');

        $swalData = [
            'type' => 'success',
            'title' => 'Başarılı',
            'message' => 'Eklenti Sepete Eklenmiştir',
        ];
        $this->dispatchBrowserEvent('islembasarili', $swalData);


    }



    public function submit()
    {
        // validate the form input
        $this->validate([
            'name' => 'required',
        ],['name.required' => 'Kupon kodu Alanı boş bırakılamaz.']);


        $sorgula=Kuponcode::where('kupon_sifre',$this->name)->where('durum',1)->first();



        if ($sorgula){
            if (!$sorgula->indirim_orani==""){
                $this->deger = $sorgula->indirim_orani;
                // success message

                session()->flash('indirim_oran', 'Form submitted successfully.');
                session()->put('indirimorani', $this->deger);

            }else{
                $this->deger = $sorgula->indirim_miktar;
                // success message

                session()->flash('indirim_miktar', 'Form submitted successfully.');
                session()->put('indirimmiktari', $this->deger);

            }



        }else{
            session()->flash('basarisiz', 'Böyle kupon yok.');

        }

        // send email or save to database, etc
        // ...


    }

}
