<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Datatables\Admin\Shop\OrdersDataTable;
use App\Http\Controllers\Controller;
use App\Repositories\Shop\Invoices;
use App\Repositories\Shop\OfferStocks;
use App\Repositories\Shop\OrderMails;
use App\Repositories\Shop\Orders;
use Illuminate\Http\Request;

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

    public function create()
    {
        return view('Admin.Shop.Orders.create');
    }

    public function show($id)
    {
        $data = Orders::get($id);

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

    public function edit($id)
    {
        $data = Orders::edit($id);

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

    public function store(Request $request)
    {
        $previousStatus = null;
        if ($request->has('id')) {
            $previousStatus = Orders::get($request->input('id'))->status;
        }

        $newStatus = $request->input('status');

        // Interdire l'annulation si la facture a des paiements
        if ($previousStatus != 4 && $newStatus == 4 && $request->has('id')) {
            $order = Orders::get($request->input('id'), ['invoice']);
            if ($order->invoice) {
                $totalPaid = Invoices::getPayments($order->invoice->id);
                if ($totalPaid > 0) {
                    return redirect()->back()->withInput()->with(
                        'growl',
                        ['Impossible d\'annuler cette commande : la facture a déjà été réglée ('.number_format($totalPaid, 2, ',', ' ').' €). Veuillez d\'abord gérer le remboursement.', 'danger']
                    );
                }
            }
        }

        // Vérifier le stock avant de dés-annuler une commande
        if ($previousStatus == 4 && $newStatus != 4) {
            $insufficients = OfferStocks::checkStockForOrder($request->input('id'));
            if (! empty($insufficients)) {
                $messages = [];
                foreach ($insufficients as $item) {
                    $messages[] = $item['name'].' (stock : '.$item['stock'].', requis : '.$item['quantity'].')';
                }

                return redirect()->back()->withInput()->with(
                    'growl',
                    ['Impossible de réactiver cette commande, stock insuffisant : '.implode(' ; ', $messages), 'danger']
                );
            }
        }

        $order = Orders::store($request->all());
        if ($order->wasChanged('status')) {
            switch ($order->status) {
                case 1:
                    OrderMails::sendPreparation($order->id);
                    break;
                case 2:
                    OrderMails::sendShipping($order->id);
                    break;
                case 4:
                    OfferStocks::restoreStock($order->id);
                    break;
                default:
                    if ($previousStatus == 4) {
                        OfferStocks::decreaseStockForOrder($order->id);
                    }
            }
        }

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

    public function delete($id)
    {
        return Orders::destroy($id);
    }

    public function download($id)
    {
        return Orders::download($id);
    }
}
