<?php

namespace App\Http\Controllers\Shop;

use App\Datatables\Shop\CustomerOrdersDataTable;
use App\Http\Requests\Shop\StoreOrderPost;
use App\Repositories\Core\User\ShopCart;
use App\Repositories\Shop\Baskets;
use App\Repositories\Shop\Contents;
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(CustomerOrdersDataTable $dataTable)
    {
        if (Customers::isNotConnected()) {
            abort(403);
        }
        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();
            $deliveries = Deliveries::getByCustomer();

            $data = [
                'customer' => $customer ? $customer->toArray() : false,
                'basket' => Baskets::getBasketTotal(),
                'deliveries' => $deliveries ? $deliveries->toArray() : [],
                'delivery_types' => DeliveryTypes::getWithPrice(Baskets::getWeight()),
            ];

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

        return redirect()->route('home');
    }

    public function store(StoreOrderPost $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'], $data['delivery_type_id'] ?? false);
        $order = Orders::saveOrder($data);

        if ($order) {
            if ($data['payment_type'] === '1') {
                return Paybox::makeAuthorizationRequest($order);
            }
            OrderMails::sendOrderConfirmed($order->id);

            return redirect()->route('Shop.Orders.confirmed');
        }

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

    public function confirmed()
    {
        ShopCart::clear();
        $content = Contents::getOrderConfirmedContent();

        return view('Shop.Orders.confirmed', ['content' => $content]);
    }

    public function getPdf($uuid)
    {
        return Orders::getPdfByUUID($uuid);
    }
}
