<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\SalesOrder;
use App\SalesOrderComment;
use DB;
use App\Http\Controllers\SalesOrderController;

class ApiController extends Controller
{
    function track_order($order_name, $domain)
    {
        $order = SalesOrder::where('order_name', $order_name)->first();

        if(is_null($order)){
            return response()->json(['response' => ['status' => 'Error']]);
        }

        $brand = DB::table('brands')->where('name', $domain)->first();

        if($order->brand_id != $brand->id){
            return response()->json(['response' => ['status' => 'Error']]);
        }

        if(!is_null($brand)){
            $getApi = shopify_get_order($brand->api_target, $order->order_id);
        } else {
            echo 'no such order';
            die;
        }

        $items = [];

        $order_items = DB::table('sales_order_items')->where('sales_order_id', $order->id)->get();

        foreach($order_items as $item){
            $items[] = ['image' => $item->product_image_url, 'name' => $item->name, 'sku' => $item->sku, 'quantity' => $item->quantity, 'price' => $item->price];
        }

        $data = json_decode($getApi, True);

        if($data['order']['fulfillments'] != []){
            $courier = $data['order']['fulfillments'][0]['tracking_company'];
            $tracking = $data['order']['fulfillments'][0]['tracking_number'];
        } else {
            $courier = 'N/A';
            $tracking = 'N/A';
        }

        $total_price = $order->total_price;
        
        $message = UcFirst($order->tags);

        return response()->json(['response' => ['status' => 'Success', 'tags' => $message, 'courier' => $courier, 'tracking' => $tracking, 'order_name' => $order_name, 'items' => $items, 'total_price' => $total_price]]);
    }


    public function fetch_custom_order(Request $request)
    {
        $order_array = [];

        if($request->has('order_name'))
        {
            $order = DB::table('sales_orders')->where('sales_orders.order_name', $request->order_name)->first();

            if(!is_null($order)){
                $order_items = DB::table('sales_order_items')->where('sales_order_id', $order->id)->get();
                $shippingDetails = DB::table('sales_order_addresses')->where([['sales_order_id', $order->id],['type', 'shipping']])->first();
                $billingDetails = DB::table('sales_order_addresses')->where([['sales_order_id', $order->id],['type', 'billing']])->first();
                $customerDetails = DB::table('sales_order_customers')->where('sales_order_id', $order->id)->first();
            } else {
                return false;
            }

            $order_array = ['order' => $order, 'itemData' => $order_items , 'shippingDetails' => $shippingDetails, 'billingDetails' => $billingDetails, 'customerDetails' => $customerDetails];

            return json_encode($order_array);
        }
    }


    public function fetch_custom_order_shipped(Request $request)
    {
        $order_array = [];

        if($request->has('order_name'))
        {
            $order = DB::table('sales_orders')->where('sales_orders.order_name', $request->order_name)->where('tags','Shipped')->first();

            if(!is_null($order)){
                $order_items = DB::table('sales_order_items')->where('sales_order_id', $order->id)->get();
                $shippingDetails = DB::table('sales_order_addresses')->where([['sales_order_id', $order->id],['type', 'shipping']])->first();
                $billingDetails = DB::table('sales_order_addresses')->where([['sales_order_id', $order->id],['type', 'billing']])->first();
                $customerDetails = DB::table('sales_order_customers')->where('sales_order_id', $order->id)->first();
            } else {
                return false;
            }

            $order_array = ['order' => $order, 'itemData' => $order_items , 'shippingDetails' => $shippingDetails, 'billingDetails' => $billingDetails, 'customerDetails' => $customerDetails];

            return json_encode($order_array);
        }
    }
    public function fetch_custom_order_shipped_post(Request $request)
    {
        $order_array = [];

        if($request->has('order_name'))
        {

            $order = SalesOrder::where('sales_orders.order_name', $request->order_name)->update([
                'tags' => 'Return',          
            ]);


            return json_encode($order_array);
        }
    }



    public function connector_update_order(Request $request)
    {
        if(!$request->has('order_id')){
            echo 'missing order id'; 
            die;
        }

        if(!$request->has('tags')){
            echo 'missing tags'; 
            die;
        }

        $order = DB::table('sales_orders')->where('order_id', $request->order_id)->update(array(
            'tags' => $request->tags
        ));
    }

    public function kayseria_check_for_emp_coupon($id){
        $order = shopify_get_request('https://533055c839147f023090630d816a977c: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@kayseria-pakistan.myshopify.com/admin/api/2021-07/orders/'.$id.'.json');
        $order = json_decode($order, true);

        if(is_null($order)){
            return response()->json(['status' => 'failure', 'message' => 'Order not found']);
        }
        
        $order = $order['order'];

        $coupon_code = null;

        foreach($order['discount_codes'] as $counpon){
            if(strpos($counpon['code'], 'KYBlgOc21-') !== false){
                $coupon_code = $counpon['code'];
            }
        }

        if(is_null($coupon_code)){
            return response()->json(['status' => 'failure', 'message' => 'Coupon code not found']);
        }

        $price = $order['total_price']+$order['total_discounts'];

        if($price > 30000){
            shopify_create_transactions('https://533055c839147f023090630d816a977c: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@kayseria-pakistan.myshopify.com', $id, '{ "transaction": { "kind": "void" } }');
            
            sleep(1);
            shopify_cancel_order('https://533055c839147f023090630d816a977c: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@kayseria-pakistan.myshopify.com', $id, '{ }');
            
            $coupons = shopify_get_request('https://533055c839147f023090630d816a977c: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@kayseria-pakistan.myshopify.com/admin/api/2021-10/price_rules/1092473880795/discount_codes.json');
            $coupons = json_decode($coupons, true)['discount_codes'];
                
            foreach($coupons as $_coupon){
                if($_coupon['code'] == $coupon_code){
                    $coupon_code_id = $_coupon['id'];
                    $price_rule_id = $_coupon['price_rule_id'];
                    
                    sleep(1);
                    shopify_delete_request('https://533055c839147f023090630d816a977c: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@kayseria-pakistan.myshopify.com/admin/api/2021-10/price_rules/'.$price_rule_id.'/discount_codes/'.$coupon_code_id.'.json', '{}');
                    
                    sleep(1);
                    shopify_post_request('https://533055c839147f023090630d816a977c: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@kayseria-pakistan.myshopify.com/admin/api/2021-10/price_rules/1092473880795/batch.json', '{     "discount_codes":[{"code":"'.$coupon_code.'"}] }');
                }
            }

            return response()->json(['status' => 'success', 'message' => $order['name']]);
        }else{
            return response()->json(['status' => 'failure', 'message' => 'Order passed, grand total is under control']);
        }
    }

    public function missing_orders_cron($id){
        $brand = DB::table('brands')->where('id', $id)->first();

print_r($brand);die;

        $last_order_id = DB::table('missing_orders_queue')->where('brand_id', $id)->first();
        
        if(is_null($last_order_id)){
            DB::table('missing_orders_queue')->insert([ 'brand_id' => $id, 'last_order_id' => 0, 'created_at' => now(), 'updated_at' => now()]);
        }

        $orders = shopify_get_request($brand->api_target.'/admin/api/2021-10/orders.json?status=any&fields=name,id&limit=250&since_id='.$last_order_id->last_order_id);
        $orders = json_decode($orders, true)['orders'];

        $set_last_order_id = null;

        if(count($orders) > 0){
            foreach($orders as $order){
                $if_order = SalesOrder::where('order_id', $order['id'])->first();
                $set_last_order_id = $order['id'];

                if(is_null($if_order)){
                    DB::table('missing_orders_queue_log')->insert([ 'brand_id' => $id, 'order_name' => $order['name'], 'order_id' => $order['id'], 'created_at' => now(), 'updated_at' => now() ]);
                }
            }
        }

        DB::table('missing_orders_queue')->where('brand_id', $id)->update(['last_order_id' => $set_last_order_id, 'updated_at' => now()]);
    }

    public function missing_order_cron_import(){
        $order = DB::table('missing_orders_queue_log')->where('status', 0)->first();
        $brand = DB::table('brands')->where('id', $order->brand_id)->first();

        $orders = shopify_get_request($brand->api_target.'/admin/api/2021-10/orders/'.$order->order_id.'.json');
        $orders = json_decode($orders, true);
        
        foreach($orders as $_order){
            $controller_class = new SalesOrderController;
            $create_order = $controller_class->create_order($brand->id, $brand->api_target, $_order);

            if($create_order){
                DB::table('missing_orders_queue_log')->where('id', $order->id)->update([ 	'status' => 1, 	'updated_at' => now() ]);
                echo 'Order '.$order->order_name.' has been imported';
            }
        }
    }


    //cron for fetch missing items
    public function fetch_missing_items()
    {
        $item_array = [];
        $item_ids = [];

        $missingItems = DB::table('fetched_item_count')->where([['total_item_count', '!=', DB::raw('items_fetched')], ['flagged', 0]])->first();
       
        if(is_null($missingItems)){
            die;
        }

        $items = DB::table('sales_order_items')->where('sales_order_id', $missingItems->sales_order_id)->get();
        
        foreach($items as $ids){
            $item_ids[] = $ids->sales_order_id.'_'.$ids->product_id;
        }

        $getParams = DB::table('brands')->where('id', $missingItems->brand_id)->first();

        $getApi = shopify_get_order($getParams->api_target, $missingItems->order_id);
        
        $data = json_decode($getApi, True);
        
        $order_data = $data['order']['line_items'];
        
        $counter = 0;

        foreach($order_data as $item){
            $check_order = DB::table('sales_order_items')->where([['sales_order_id', $missingItems->sales_order_id], ['product_id', $item['product_id']], ['sku', $item['sku']]])->first();
            
            if(!is_null($check_order)){
                continue;
            }
            
            $variant_id = $item['variant_id'];
            $product_id = $item['product_id'];

            // order products for discount
            $order_products = shopify_get_product($getParams->api_target, $product_id);
            $get_all_products = json_decode($order_products, true);
            
            if(!is_array($get_all_products)){
                DB::table('fetched_item_count')->where('sales_order_id', $missingItems->sales_order_id)->update(array(
                    'flagged' => 1
                ));
                echo 'Product Name: '.$item['name'].' Product ID: '.$product_id.' and variant ID: '.$variant_id.' not found<br>';
                continue;
            }

            $compare_at_price = '';
            
            foreach($get_all_products['product']['variants'] as $line){
                $compare_at_price = $line['compare_at_price'];
            }

            $shopify_product_variant = shopify_get_variant($getParams->api_target, $variant_id);
            
            $product_variant = json_decode($shopify_product_variant, true);
            
            if(is_array($product_variant)){
                if(!array_key_exists('errors', $product_variant)){
                    $shopify_products_images = shopify_get_product_images($getParams->api_target, $product_id);
    
                    $product_images = json_decode($shopify_products_images, true);

                    $item_array[] = ['sales_order_id' => $missingItems->sales_order_id, 'title' => $item['title'], 'name' => $item['name'], 'sku' => $item['sku'], 'quantity' => $item['quantity'], 'product_id' => $item['product_id'], 'price' => $item['price'], 'vendor' => $item['vendor'], 'upc' => $product_variant['variant']['barcode'], 'color' => $product_variant['variant']['option1'], 'size' => $product_variant['variant']['option2'], 'product_image_url' => empty($product_images['images'])? '' : $product_images['images'][0]['src'], 'compare_at_price' => $compare_at_price, 'order_product_id' => $item['id']];   
                }
            }else{
                $item_array[] = ['sales_order_id' => $missingItems->sales_order_id, 'title' => $item['title'], 'name' => $item['name'], 'sku' => $item['sku'], 'quantity' => $item['quantity'], 'product_id' => $item['product_id'], 'price' => $item['price'], 'vendor' => $item['vendor'], 'upc' => $get_all_products['product']['variants'][0]['barcode'], 'color' => $get_all_products['product']['variants'][0]['option1'], 'size' => $get_all_products['product']['variants'][0]['option2'], 'product_image_url' => empty($product_images['images'])? '' : $product_images['images'][0]['src'], 'compare_at_price' => $compare_at_price, 'order_product_id' => $item['id']];   
            }

            $item_ids[] = $missingItems->sales_order_id.'_'.$item['product_id'];
            $counter++;
            sleep(1);
        }
        
        $create_sales_order_items = DB::table('sales_order_items')->insert($item_array);

        DB::table('fetched_item_count')->where('sales_order_id', $missingItems->sales_order_id)->update(array(
            'items_fetched' => $counter + $missingItems->items_fetched
        ));

        echo $missingItems->sales_order_id;
    }




    public function missing_items($order_name)
    {
        $item_array = [];
        $item_ids = [];

        $missingItems = DB::table('fetched_item_count')->where('total_item_count', '!=', DB::raw('items_fetched'))->first();
        if(is_null($missingItems)){
            die;
        }
        $items = DB::table('sales_order_items')->where('sales_order_id', $missingItems->sales_order_id)->get();

        foreach($items as $ids){
            $item_ids[] = $ids->sales_order_id.'_'.$ids->product_id;
        }

        $getParams = DB::table('brands')->where('id', $missingItems->brand_id)->first();

        $getApi = shopify_get_order($getParams->api_target, $missingItems->order_id);
        
        $data = json_decode($getApi, True);
        $order_data = $data['order']['line_items'];

        $counter = 0;

        foreach($order_data as $item){
            $check_order = DB::table('sales_order_items')->where([['sales_order_id', $missingItems->sales_order_id], ['product_id', $item['product_id']], ['sku', $item['sku']]])->first();
            
            if(!is_null($check_order)){
                continue;
            }

            echo $item['sku'].'<br>';

            $variant_id = $item['variant_id'];
            $product_id = $item['product_id'];

            // order products for discount
            $order_products = shopify_get_product($getParams->api_target, $product_id);
            $get_all_products = json_decode($order_products, true);
            
            if(!is_array($get_all_products)){
                continue;
            }

            $compare_at_price = '';
            
            foreach($get_all_products['product']['variants'] as $line){
                $compare_at_price = $line['compare_at_price'];
            }

            $shopify_product_variant = shopify_get_variant($getParams->api_target, $variant_id);
            
            $product_variant = json_decode($shopify_product_variant, true);
            
            if(is_array($product_variant)){
                if(!array_key_exists('errors', $product_variant)){
                    $shopify_products_images = shopify_get_product_images($getParams->api_target, $product_id);
    
                    $product_images = json_decode($shopify_products_images, true);

                    $item_array[] = ['sales_order_id' => $missingItems->sales_order_id, 'title' => $item['title'], 'name' => $item['name'], 'sku' => $item['sku'], 'quantity' => $item['quantity'], 'product_id' => $item['product_id'], 'price' => $item['price'], 'vendor' => $item['vendor'], 'upc' => $product_variant['variant']['barcode'], 'color' => $product_variant['variant']['option1'], 'size' => $product_variant['variant']['option2'], 'product_image_url' => empty($product_images['images'])? '' : $product_images['images'][0]['src'], 'compare_at_price' => $compare_at_price, 'order_product_id' => $item['id']];   
                }
            }else{
                $item_array[] = ['sales_order_id' => $missingItems->sales_order_id, 'title' => $item['title'], 'name' => $item['name'], 'sku' => $item['sku'], 'quantity' => $item['quantity'], 'product_id' => $item['product_id'], 'price' => $item['price'], 'vendor' => $item['vendor'], 'upc' => $get_all_products['product']['variants'][0]['barcode'], 'color' => $get_all_products['product']['variants'][0]['option1'], 'size' => $get_all_products['product']['variants'][0]['option2'], 'product_image_url' => empty($product_images['images'])? '' : $product_images['images'][0]['src'], 'compare_at_price' => $compare_at_price, 'order_product_id' => $item['id']];   
            }

            $item_ids[] = $missingItems->sales_order_id.'_'.$item['product_id'];
            $counter++;
            sleep(1);
        }
        
        $create_sales_order_items = DB::table('sales_order_items')->insert($item_array);

        DB::table('fetched_item_count')->where('sales_order_id', $missingItems->sales_order_id)->update(array(
            'items_fetched' => $counter + $missingItems->items_fetched
        ));

        // dd($item_array);
    }
}
