<?php namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Cms\Classes\Controller;
use Illuminate\Http\Request;
use AhmadFatoni\ApiGenerator\Helpers\Helpers;
use Illuminate\Support\Facades\Validator;

use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\Orders;
use TPS\Birzha\Models\OrderItems;
use TPS\Birzha\Models\VendorSales;
use RainLab\User\Models\User as UserClient;
use Sms\Sms\Models\SmsSender;
use RainLab\Translate\Models\Message;
use App;
use Config;

class OrderApiController extends Controller
{
	protected $Order;

    protected $helpers;

    public function __construct(Orders $Order, Helpers $helpers)
    {
        parent::__construct();
        $this->Orders    = $Order;
        $this->helpers          = $helpers;
    }



    public function createOrder(Request $request){
        
        $data = $request->all();
        
        $validator = Validator::make($data, [
           'note' => 'required',
           'address' => 'required',
           'items' => 'required',
        ]);
        
       

       // $validator = $this->validateForm($data, $rules);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
       
        //dd($data);
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        $order = new Orders;
        
        $order->user_id = $currentUser->id;
        $order->note = $data["note"];
        $order->address = $data["address"];
        $order->status = "new";
        $order->save();
        
        
        $this->sendSMS($currentUser->username, 'Siz üstünlikli sargyt etdiňiz. Menejerimiz siz bilen habarlaşar');
        //   [{"item":34,"qty":1},{"item":35,"qty":3}]
        
        $orderItem = new OrderItems;
        $orderItem->order_id = $order->id;
        $orderItem->items = json_decode($data["items"]);
        $orderItem->save();
        
       // dd($orderItem->items[0]["item"]);
        
        for ($i = 0; $i < count($orderItem->items); $i++) {
            
            $vendorSale = new VendorSales;
            $vendorSale->order_id = $order->id;
            $vendorSale->vendor_id =  $orderItem->items[$i]["vendor_id"];
            $vendorSale->product_id = $orderItem->items[$i]["item"];
            $vendorSale->qty = $orderItem->items[$i]["qty"];
            $vendorSale->price = $orderItem->items[$i]["price"];
            $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, 'Gurluşyk programmasyndan size sargyt edildi');
         }
        
        
        if ($order && $orderItem && $vendorSale){
            
            //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$order]);
            return response()->json($order, 200);
            
        }else{
        
            return $this->helpers->apiArrayResponseBuilder(400, 'fail');
            
        }
       
    }
    
    
    public function myOrders(Request $request){
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        
        $orders = Orders::where("user_id", $currentUser->id)->with('order_items')->orderBy('id', 'DESC')->paginate(12);
                                                      
        for ($i = 0; $i < count($orders); $i++) {        
            
            $product_items = $orders[$i]->order_items[0]->items;
            $productsCollectId = [];
            
            for ($ii = 0; $ii < count($product_items); $ii++) {
               
                $productsCollectId[] = (int)$product_items[$ii]["item"];
                
            }
            
            $orders[$i]->products = Product::whereIn("id", $productsCollectId)
                                    ->with(['translations:locale,model_id,attribute_data',
                                            'images:attachment_id,attachment_type,disk_name,file_name',
                                            'vendor:id,name,email,type,logo,banner,shop_title,slogan,is_instagram,web2',
                                            'place',])
                                    ->withTrashed()
                                    ->get();
                                    
            $orders[$i]->makeHidden(['order_items']);
        }
        
        return response()->json($orders, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    
    public function makeTemplate($sales)
    {
        //$asset = new \Cms\Classes\Asset($this->controller->getTheme());
        
       
        $html = "<!DOCTYPE html>
            <html>

            <head>
                <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'>
                <title>SARGYT #NO:" . $sales[0]->order_id . "</title>
       
                <style>
                    table.table-bordered{
                        border:1px solid black;
                        margin-top:20px;
                    }
                    table {
                      width: 100%;
                    }
                    table.table-bordered > thead > tr > th{
                        border:1px solid black;
                    }
                    table.table-bordered > tbody > tr > td{
                        border:1px solid black;
                    }
                    table.table-bordered > tbody > tr > th{
                        border:1px solid black;
                    }

                    .tPadding{
                        padding: 4px !important;
                    }

                    .tFirsTd{
                        width: 5%;
                    }

                    tr{
                        height: 15px;
                    }
                </style>
            </head>

            <body>
                  
                    <div class='row '>
                        <table class='table-borderless' style='margin-bottom: 15px;border-bottom: 3px solid black;'>
                            <tbody>
                                <tr style='text-align: center;'>
                                    <td style='text-align: center;font-weight: bold;font-size: 17px;'>Sargyt No: #".$sales[0]->order_id." Sene: ".$sales[0]->created_at->format('d.m.Y')."</td>
                                </tr>
                            </tbody>
                        </table>

                        <table class='table-borderless' style='margin-bottom: 5px;'>
                            <tbody style='font-size: 15px;'>
                                <tr>
                                    <td style='text-align: left;'>Ady: ".$sales[0]->order->user->name."</td>
                                </tr>
                                <tr>
                                    <td style='text-align: left;'>Telefon: +993 ".$sales[0]->order->user->username."</td>
                                </tr>
                                <tr>
                                    <td style='text-align: left;'>Salgy: ".$sales[0]->order->address."</td>
                                </tr>
                                <tr>
                                    <td style='text-align: left;'>Telefon2: +993 ".$sales[0]->order->phone."</td>
                                </tr>
                                <tr>
                                    <td style='text-align: left;'>Bellik: ".$sales[0]->order->note."</td>
                                </tr>
                            </tbody>
                        </table>

                    </div>

                    <div class='row mt-2'>
                        <table class='table table-bordered' style='margin-bottom: 5px;' style='width: 100% !important;'>
                            <thead style='background: black;color: white;font-size: 14px;'>
                                <tr>
                                    <th scope='col' style='font-weight: normal;' class='tFirsTd tPadding'>#</th>
                                    <th scope='col' style='font-weight: normal;text-align: center;' class='tPadding'>Suraty</th>
                                    <th scope='col' style='font-weight: normal;text-align: center;' class='tPadding'>Ady</th>
                                    <th scope='col' style='font-weight: normal;text-align: center;' class='tPadding'>Bahasy</th>
                                </tr>
                            </thead>
                            <tbody style='font-size: 14px;'>";

                            for ($ii = 0; $ii < count($sales); $ii++) {
                             
                                $html .="<tr>
                                            <td style='text-align: center;'>".($ii+1)."</td>
                                            <td style='text-align: center;'><img src='".$sales[$ii]->product->images[0]->path."' style='width: 90px !important;'</td>
                                            <td style='text-align: center;'>".$sales[$ii]->product->name."</td>
                                            <td style='text-align: center;'>".$sales[$ii]->product->price." TMT</td>
                                        </tr>";
                                
                            }
            
                    $html .="</tbody></table></div></body></html>";
            

        return (string) $html;
    }

   
       
    public function onSavePdf($sales)
    {
         
        $pdf = App::make('dompdf.wrapper');
        $pdf->loadHTML($this->makeTemplate($sales))->setWarnings(false);
        $pdf->stream();
         
        $pdf->save('storage/app/media/pdf/invoice_no_' . $sales[0]->order_id . '_'.$sales[0]->order->user->username.'.pdf');
     
        $path = Config::get('app.url') . '/storage/app/media/pdf/invoice_no_' . (string)$sales[0]->order_id . '_'.(string)$sales[0]->order->user->username.'.pdf';
     
        return (string)$path;
    }
    
    
    public function mySales(Request $request){
        
        $data = $request->all();
        
        $validator = Validator::make($data, [
           'order_id' => 'required',
        ]);

       // $validator = $this->validateForm($data, $rules);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        
        $sales = VendorSales::where('vendor_id', $currentUser->id)->where('order_id', $data["order_id"])->with(['order.user', 'product.images:attachment_id,attachment_type,disk_name,file_name', 'product.place', 'product.vendor:id,name,email,type,logo,banner,shop_title,slogan,is_instagram'])->orderBy('id', 'DESC')->paginate(15);
        
       
       if(count($sales) > 0){
        
            $sales[0]->pdf_url = $this->onSavePdf($sales);
       }
       
        
       return response()->json($sales, 200);
        
        
    }
    
    public function mySaleOrders(Request $request){
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        
        $sales = VendorSales::select('id', 'order_id', 'created_at', 'status')->with(['order.user:id,name,username', 'order:id,user_id,note,phone,address'])->where('vendor_id', $currentUser->id)->groupBy('order_id')->orderBy('id', 'DESC')->paginate(15);
        
       
        
        return response()->json($sales, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    
    public function checkVendorSales(){
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        $counter = 0;
        
        $sales = VendorSales::where('vendor_id', $currentUser->id)->where('status', 'new')->groupBy('order_id')->get();
        
        
        
        $newOrders = array(
            "new_order_count" => count($sales),
        );
        
        return response()->json($newOrders, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    
    public function confirmOrder(Request $request){
        $data = $request->all();
        
        $validator = Validator::make($data, [
           'order_id' => 'required',
        ]);
        
       // $validator = $this->validateForm($data, $rules);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
       
       
        //dd($data);
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        $vendorOrders = VendorSales::where('order_id', $data["order_id"])->get();
        $order = Orders::where('id', $data["order_id"])->first();
        
        if((count($vendorOrders) != 0) && ($vendorOrders[0]->vendor_id == $currentUser->id)){
        
            for ($i = 0; $i < count($vendorOrders); $i++) {
                
                $vendorOrders[$i]->status = "completed";
                $vendorOrders[$i]->save();
                
            }
            
            $order->status = "completed";
            $order->save();
        
        }
        
        
        if ($vendorOrders){
            
            //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$order]);
            return response()->json($vendorOrders, 200);
            
        }else{
        
            return $this->helpers->apiArrayResponseBuilder(400, 'fail');
            
        }
       
    }
    
    protected function sendSMS($phone, $message){
        
        $smsSender = new SmsSender();
        $smsSender->phone = (string)'+993'.$phone;
        $smsSender->message = strval($message);
        $smsSender->save();
        
    }

    public static function getAfterFilters() {return [];}
    public static function getBeforeFilters() {return [];}
    public static function getMiddleware() {return [];}
    public function callAction($method, $parameters=false) {
        return call_user_func_array(array($this, $method), $parameters);
    }

}
