<?php namespace TPS\Birzha\Components;

use Cms\Classes\ComponentBase;
use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\Orders;
use TPS\Birzha\Models\VendorSales as VSales;
use Input;
use Flash;

class SingleSale extends ComponentBase
{
    /**
     * @var Collection A collection of user's posts
     */
    public $sales;
    public $order;
    
    
    public function componentDetails()
    {
        return [
            'name'        => 'Sale order detail',
            'description' => 'Sale order products'
        ];
    }

    public function defineProperties()
    {
        return [
            'id' => [
                'title' => 'Get order :id',
                'description' => 'Get order :id',
                'type' => 'string',
                'default' => ''
            ],
            'perPage' => [
                'title' => 'Number of vendor sales',
                'description' => 'How many vendor sales do you want to display',
                'default' => 12,
                'validationPattern' => '^[0-9]+$',
                'validationMessage' => 'Only numbers allowed'
            ],
        ];
    }

    public function onConfirm(){
        $data = post();

        $vendorOrders = VSales::where('order_id', $data["order_id"])->get();
        
        if((count($vendorOrders) != 0) && ($vendorOrders[0]->vendor_id == \Auth::user()->id)){
            
            for ($i = 0; $i < count($vendorOrders); $i++) {
                $vendorOrders[$i]->status = "completed";
                $vendorOrders[$i]->save();
            }
            
            $order = Orders::find($data["order_id"]);
            $order->status = "completed";
            $order->save();
            
            Flash::success('Zakaz kabul edildi');
            return \Redirect::back();

        }else{
            Flash::error('Ýalňyşlyk ýüze çykdy');    
            return \Redirect::back();
        }
    }


    public function onRun() {
        $this->order = $this->loadOrder();
        $this->sales = $this->loadSaleOrderDetail();
        
    }

    protected function loadSaleOrderDetail() {
        $perPage = $this->property('perPage');
        $sales = VSales::where('vendor_id', \Auth::user()->id)
                                    ->where('order_id', $this->property('id'))
                                    ->with(['order.user', 'product'])
                                    ->orderBy('id', 'DESC')
                                    ->paginate(15);
        //dd($sales);
        return $sales;
    }
    
    protected function loadOrder() {
        $order = Orders::where('id', $this->property('id'))->first();
        return $order;
    }
    
    

    
}
