<?php

namespace App\Http\Controllers\API\Client\Order;

use App\Http\Controllers\Controller;
use App\MasterInventory;
use App\Order;
use App\OutletClient;
use App\ProductOnPackaging;
use App\ProductRequest;
use App\Stock;
use App\StockOutProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use JWTAuth;

class IndexController extends Controller
{
    public function saveOrder(Request $request)
    {
        $codeOrder = Str::random(10);
        $customer = JWTAuth::parseToken()->authenticate();
        $sales = OutletClient::where('phone', $customer->id_employee)->first();

        $order = new Order();
        $order->code_order = $codeOrder;
        $order->type_order = $request->typeOrder;
        $order->customer_id = $customer->id;
        $order->sales_id = $sales->sales;
        $order->total_payment = $request->totalPayment;
        $order->save();

        for ($i = 0, $iMax = count($request->itemsOrder); $i < $iMax; $i++) {
            $productReq = new ProductRequest();
            $productReq->code_order = $codeOrder;
            $productReq->product_id = MasterInventory::where('name', $request->itemsOrder[$i]['name'])->first()->id;
            $productReq->qty = $request->itemsOrder[$i]['qty'];
            $productReq->save();
        }

        return response('Pesanan anda berhasil di process!', 200);
    }

    public function getOrder()
    {
        $order = Order::leftJoin('users as customer', 'customer.id', '=', 'orders.customer_id')
            ->leftJoin('users as sales', 'sales.id', '=', 'orders.sales_id')
            ->where('orders.status', 'Process Pengerjaan')
            ->select('customer.name as customer', 'customer.id as idCustomer', 'sales.name as sales', 'sales.id as idSales', 'orders.id as idOrder', 'orders.status', 'orders.code_order', 'orders.created_at')
            ->orderBy('orders.id', 'DESC')
            ->get();

        return response($order, 200);
    }

    public function getOrderList($idOrder)
    {
        $kodeOrder = Order::find($idOrder);
        $productRequest = ProductRequest::leftJoin('master_inventories', 'master_inventories.id', '=', 'product_requests.product_id')
            ->where('product_requests.code_order', $kodeOrder->code_order)
            ->select('product_requests.id', 'master_inventories.name', 'product_requests.qty', 'product_requests.product_id as idProduct')
            ->get();

        return response($productRequest, 200);
    }

    public function checkQty($idProduct)
    {
        $stock = Stock::find($idProduct);
        return response($stock, 200);
    }

    public function processOrder(Request $request)
    {
        $productRequest = ProductRequest::where('code_order', $request->codeOrder)->get();
        $idProduct = [];
        for ($i = 0, $iMax = count($productRequest); $i < $iMax; $i++) {
            array_push($idProduct, $productRequest[$i]['product_id']);
            $checkStock = Stock::leftJoin('master_inventories', 'master_inventories.id', '=', 'stocks.id')
                ->where('stocks.id', $productRequest[$i]['product_id'])
                ->select('stocks.stock', 'master_inventories.name')
                ->first();
            if ((float)$checkStock->stock < $productRequest[$i]['qty']) {
                return response([
                    'err' => true,
                    'msg' => 'Stok '.$checkStock->name.' tidak mencukupi'
                ], 200);
            }
        }

        $idOrder = Order::where('code_order', $request->codeOrder)
            ->first();

        $dataPackaging = ProductOnPackaging::leftJoin('master_inventories', 'master_inventories.id', '=', 'product_on_packagings.product_id')
            ->leftJoin('master_inventories as packaging', 'packaging.id', '=', 'product_on_packagings.packaging_id')
            ->whereIn('product_on_packagings.product_id', $idProduct)
            ->where('product_on_packagings.status_stock', 'OPEN')
            ->select('master_inventories.name as nameProduct',
                'product_on_packagings.product_id as productId',
                'product_on_packagings.id',
                'product_on_packagings.qty_product as qty',
                'product_on_packagings.multiple',
                'packaging.name as packagingName')
            ->get();

        return response([
            'err' => false,
            'msg' => $dataPackaging,
            'idOrder' => $idOrder->id
        ], 200);
    }

    public function sendOrder(Request $request)
    {
        $order = Order::where('code_order', $request->codeOrder)->first();
        for ($i = 0, $iMax = count($request->product); $i < $iMax; $i++) {
            $packaging = ProductOnPackaging::find($request->product[$i]['idPackaging']);
            $stock = Stock::find($packaging->product_id);
            $stock->stock = (float)$stock->stock - ((int)$packaging->qty_product * (int)$request->product[$i]['count']);
            $stock->save();

            $stockOut = new StockOutProduct();
            $stockOut->product_id = $packaging->product_id;
            $stockOut->sales_id = $order->sales_id;
            $stockOut->customer_id = $order->customer_id;
            $stockOut->packaging_id = $request->product[$i]['idPackaging'];
            $stockOut->stock_out = $stock->stock;
            $stockOut->code_order = $request->codeOrder;
            $stockOut->description = 'LOREM IPSUM';
            $stockOut->save();

            if ((int)$packaging->multiple === (int)$request->product[$i]['count']) {
                $packaging->status_stock = 'CLOSED';
                $packaging->save();
            } else {
                $packaging->multiple = (int)$packaging->multiple - (int)$request->product[$i]['count'];
                $packaging->save();
            }
        }
        $order->status = 'Proces Pengiriman';
        $order->save();
        
        return response('Berhasil di proses', 200);
    }
}
