<?php namespace TPS\Birzha\Components;

use Cms\Classes\ComponentBase;
use Illuminate\Support\Facades\Config;
use October\Rain\Exception\AjaxException;
use October\Rain\Support\Facades\Event;
use TPS\Birzha\Models\Payment;
use RainLab\User\Facades\Auth;
use RainLab\User\Models\User as VendorModel;
use Validator;
use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\Orders;
use TPS\Birzha\Models\OrderItems;
use TPS\Birzha\Models\VendorSales;
use Flash;
use Sms\Sms\Models\SmsSender;
use RainLab\Translate\Models\Message;
use ValidationException;

class Checkout extends ComponentBase
{
    public function componentDetails()
    {
        return [
            'name'        => 'Checkout',
            'description' => 'Checkout page'
        ];
    }

    public function onCreateOrder(){
        $data = post();
        $rules = [
            'note' => 'required',
            'address' => 'required',
            'phone_custom' => 'required',
            'items' => 'required',
        ];

        $this->validateForm($data, $rules);

        $objects = json_decode($data["items"], true);
        if(count($objects) == 0){
            Flash::error('Haryt ýok. Ýalňyşlyk');
            return 500;
        }
         $order = new Orders;
         $order->user_id = \Auth::user()->id;
         $order->note = $data["note"];
         $order->address = $data["address"];
         $order->phone = $data["phone_custom"];
         $order->status = "new";
         $order->save();
         
         $userPhone= \Auth::user()->username;
         
         $this->sendSMS($userPhone, Message::trans('success.ordered'));
            
         $orderItem = new OrderItems;
         $orderItem->order_id = $order->id;
         $orderItem->items = json_decode($data["items"]);
         $orderItem->save();
         

         for ($i = 0; $i < count($orderItem->items); $i++) {
             $vendorSale = new VendorSales;
             $vendorSale->order_id = $order->id;
             $vendorSale->vendor_id =  $orderItem->items[$i]["vendor"];
             $vendorSale->product_id = $orderItem->items[$i]["item"];
             $vendorSale->qty = $orderItem->items[$i]["qty"];
             $vendorSale->price = $orderItem->items[$i]["price"];
             $vendorSale->note = $data["note"];
             $vendorSale->save();
         }
         
         $vendorPhones = VendorSales::where("order_id", $order->id)->with("vendor")->groupBy("vendor_id")->get();
         
         for ($x = 0; $x < count($vendorPhones); $x++) {
             $this->sendSMS($vendorPhones[$x]->vendor->username, Message::trans('success.ordered.vendor'));
         }
    
         if ($order && $orderItem && $vendorSale){
            Flash::success('Sargyt ugradyldy');
            return [
                '#checkoutMainDiv' => $this->renderPartial('@success')
            ];
         }else{
            Flash::error('Sargyt ugradylmady');
            return 500;
         }
    }
    
    protected function sendSMS($phone, $message){
        
        $smsSender = new SmsSender();
        $smsSender->phone = (string)'+993'.$phone;
        $smsSender->message = strval($message);
        $smsSender->save();
        
    }

    protected function validateForm($data, $rules) {
        $validator = Validator::make($data, $rules);

        if($validator->fails()) {
            throw new ValidationException($validator);
        }
    }
}
