<?php

namespace App\Http\Controllers;

use App\Services\Midtrans\CreateSnapTokenService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\Product;
use App\Models\District;
use App\Models\Order;
use App\Models\OrderItem;

class FashionController extends Controller
{
    public function index(Request $request)
    {
        return view('ar_fashion');
    }
    
    public function productData()
    {
        $productId = -1;
        $isNew = true;
        
        $results = Product::select('products.*','product_items.id as product_items_id','product_items.size','product_items.price','product_items.product_id','product_items.weight')
            ->join('product_items','product_items.product_id','=','products.id')
            ->where('product_items.quantity','>','0')
            ->orderBy('product_items.product_id')
            ->orderBy('product_items_id')
            ->get();
        
        foreach($results as $result)
        {
            if($result->id === $productId)
            {
                $sizes[] = array('id'=>$result->product_items_id,'name'=>$result->size,'price'=>$result->price,'weight'=>$result->weight);
                $product['sizes'] = $sizes;
                $productId = $result->id;

            }else{
                $sizes = array();

                if($isNew){
                    $product = array('id'=>$result->id,'name'=>$result->name,'img'=>'imgs/polosh/'.$result->img);
                    $sizes[] = array('id'=>$result->product_items_id,'name'=>$result->size,'price'=>$result->price,'weight'=>$result->weight);
                    $product['sizes'] = $sizes;
                    $productId = $result->id;
                    $isNew = false;

                }else{
                    $products[] = $product;

                    $product = array('id'=>$result->id,'name'=>$result->name,'img'=>'imgs/polosh/'.$result->img);
                    $sizes[] = array('id'=>$result->product_items_id,'name'=>$result->size,'price'=>$result->price,'weight'=>$result->weight);
                    $product['sizes'] = $sizes;
                    $productId = $result->id;
                    $isNew = false;
                }

            }
        }        

        $products[] = $product;
        echo json_encode($products);
    }

    public function provinceData()
    {
        $results = District::leftJoin('regencies','regencies.id','=','districts.regency_id')
            ->leftJoin('provinces','provinces.id','=','regencies.province_id')
            ->select('districts.id','districts.name as kec','regencies.name as kota','provinces.name as prov','districts.cost')
            ->get();

        $regions = array();
        foreach($results as $result)
        {
            $region = array(
                'id'=>$result->id,
                'name'=>$result->prov.", ".$result->kota.", ".$result->kec,
                'kec'=>$result->kec,
                'cost'=>$result->cost
            );
            $regions[] = $region;
        }
        echo json_encode($regions);
    }
    
    public function createOrderParams($request,$orderId)
    {
        //Rebuild item details
        $items = json_decode($request->items);
        $shippingCost = $request->shippingCost;

        $item_details = array();
        foreach($items as $each)
        {
            $item = array(
                'id' => $each->id,
                'price' => $each->price,
                'quantity' => $each->quantity,
                'name' => $each->name.' - '. $each->size,
                );
            $item_details[] = $item;
        }
        
        //Add transport fee
        $item_details[] = array(
            'id' => 'BP',
            'price' => $shippingCost,
            'quantity' => '1',
            'name' => "Ongkos Kirim"
        );

        $transaction_details = array(
            'order_id' => $orderId,
            'gross_amount' => $request->total, // no decimal allowed for creditcard
        );

        // Optional
        $billing_address = array(
            'first_name'    => $request->name,
            //'last_name'     => "LastName",
            'address'       => $request->address,
            //'city'          => "Jakarta Selatan",
            //'postal_code'   => "12345",
            'phone'         => $request->phone,
            //'country_code'  => 'IDN'
        );

        // Optional
        $shipping_address = array(
            'first_name'    => $request->name,
            //'last_name'     => "LastName",
            'address'       => $request->address,
            //'city'          => "City",
            //'postal_code'   => "12345",
            'phone'         => $request->phone,
            //'country_code'  => 'IDN'
        );

        // Optional
        $customer_details = array(
            'first_name'    => $request->name,
            //'last_name'     => "LastName",
            //'email'         => "simetris_id@yahoo.co.id",
            'phone'         => $request->phone,
            'billing_address'  => $billing_address,
            'shipping_address' => $shipping_address
        );

        // Fill transaction details
        $params = array(
            //'enabled_payments' => $enable_payments,
            'transaction_details' => $transaction_details,
            'customer_details' => $customer_details,
            'item_details' => $item_details,
        );
        return $params;
    }
    
    public function placeCod(Request $request)
    {
        $orderId = rand();
        $items = json_decode($request->items);
        $order = $this->createOrderParams($request,$orderId);

        $orderValues = array(
                'number'=>$orderId,
                'category'=>1,
                'customer'=>$request->name,
                'phone'=>$request->phone,
                'address'=>$request->address,
                'district_id'=>$request->district_id,
                'total_price'=>$request->subTotal,
                'shipping_cost'=>$request->shippingCost,
                'payment_status'=>1,
                'payment_type'=>1
            );
        
        Order::insert($orderValues);

        foreach($items as $item)
        {
            $itemValues = array(
                'order_number'=>$orderId,
                'product_items_id'=>$item->sizeId,
                'quantity'=>$item->quantity,
                'size'=>$item->size,
                'price'=>$item->price,
            );
            OrderItem::insert($itemValues);
        }

        return json_encode($order);
    }

    public function placeOrder(Request $request)
    {
        $orderId = rand();
        $items = json_decode($request->items);
        $order = $this->createOrderParams($request, $orderId);

        $midtrans = new CreateSnapTokenService($order);
        $snapToken = $midtrans->getSnapToken();

        $orderValues = array(
            'number'=>$orderId,
            'category'=>1,
            'customer'=>$request->name,
            'phone'=>$request->phone,
            'address'=>$request->address,
            'district_id'=>$request->district_id,
            'total_price'=>$request->subTotal,
            'shipping_cost'=>$request->shippingCost,
            'payment_status'=>1,
            'payment_type'=>2,
            'snap_token'=>$snapToken
        );
        Order::insert($orderValues);
        
        foreach($items as $item)
        {
            $itemValues = array(
                'order_number'=>$orderId,
                'product_items_id'=>$item->sizeId,
                'quantity'=>$item->quantity,
                'size'=>$item->size,
                'price'=>$item->price,
            );
                
            OrderItem::insert($itemValues);
        }

        return $snapToken;
    }
    
    public function paymentFinish()
    {
        return view('payment_finish');
    }
    
    public function paymentUnfinish()
    {
        return view('payment_unfinish');
    }
    
    public function paymentError()
    {
        return view('payment_error');
    }
    
}

?>