<?php

namespace App\Http\Controllers\Shop;

use App\Datatables\Shop\OrdersDataTable;
use App\Http\Controllers\Controller;
use App\Repositories\Core\User\ShopCart;
use App\Repositories\Shop\Baskets;
use App\Repositories\Shop\Customers;
use App\Repositories\Shop\Deliveries;
use App\Repositories\Shop\DeliveryTypes;
use App\Repositories\Shop\OrderMails;
use App\Repositories\Shop\Orders;
use App\Repositories\Shop\Paybox;
use App\Repositories\Shop\SaleChannels;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index(OrdersDataTable $dataTable)
    {
        return $dataTable->render('Shop.Orders.partials.list');
    }

    public function view($uuid)
    {
        $data['order'] = Orders::view($uuid);
        
        return view('Shop.Orders.view', $data);
    }

    public function pdf($uuid)
    {
        $data['order'] = Orders::getByUUID($uuid);

        return view('Shop.Orders.pdf', $data);
    }

    public function order()
    {
        if (ShopCart::count()) {
            $customer = Customers::getWithAddresses();
            
            $data = [
                'customer' => $customer ? $customer->toArray() : false,
                'basket' => ShopCart::getSummary(),
                'deliveries' => Deliveries::getAllWithSaleChannel()->toArray(),
                'sale_channel' => SaleChannels::getDefault()->toArray(),
                'delivery_types' => DeliveryTypes::getAll(),
            ];

            return view('Shop.Orders.order', $data);
        } else {
            return redirect()->route('home');
        }
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $data['customer_id'] = Customers::getId();
        $data['sale_channel_id'] = $data['sale_channel_id'] ?? SaleChannels::getDefaultID();
        $data['basket'] = Baskets::getBasketSummary($data['sale_channel_id']);
        $order = Orders::saveOrder($data);
        if ($order) {
            if ($data['payment_type'] == '1') {
                return Paybox::makeAuthorizationRequest($data['basket']['total_shipped']);
                // return redirect()->route('Shop.Payments.online');
            } else {
                return redirect()->route('Shop.Orders.confirmed');
            }
            OrderMails::sendOrderConfirmed($order->id);
        } else {
            return view('Shop.Orders.order');
        }
    }

    public function confirmed()
    {
        ShopCart::clear();

        return view('Shop.Orders.confirmed');
    }
}
