<?php

namespace App\Http\Controllers\Restaurant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Environment\Business;
use App\Models\Environment\PaymentMethod;
use App\Models\Restaurant\Comanda;
use App\Models\Restaurant\Order;
use App\Models\Restaurant\Table;

use App\Helpers\Environment\SystemModulesHelper;

class PedidoController extends Controller
{
  //* Constructor
    public function __construct() {
        $this->middleware(['auth']);
    }

  //* Basic CRUD
    public function index() {
      //- Avoid on disabled module
        if (!SystemModulesHelper::getModuleStatus('restaurant'))
            return view('errors.403');

      //- View Data
        return view('restaurant.commands.index', [
            'hotel' => Business::first(),
            'paymentMethods' => PaymentMethod::all(),
            'tables' => Table::all(),
        ]);
    }

    public function store(Request $request) {
        $order = new Order;
        $order->order_date = $request->fecha;
        $order->order_table = $request->mesa;
        $order->order_cashier = $request->cajero;
        $order->order_payment_method = $request->forma_pago;
        $order->order_total = $request->total_orden;
        $order->order_discount_percentage = $request->discount_percentage ?? 0.0;
        $order->order_discount = $request->discount ?? 0.0;
        $order->order_payment = $request->pago;
        $order->order_change = $request->cambio;
        $order->save();

        $item = $request->get('articulo');
        $category = $request->get('categoria');
        $item_quantity = $request->get('cantidad');
        $item_price = $request->get('precio_articulo');
        $subtotal = $request->get('subtotal');

        $cont = 0;
        while($cont < count($item)) {
            $comanda = new Comanda;

            $comanda->order_id = $order->id;

            $comanda->item = $item[$cont];
            $comanda->category_id = $category[$cont] ?? null;
            $comanda->item_quantity = $item_quantity[$cont];
            $comanda->item_price = $item_price[$cont];
            $comanda->subtotal = $subtotal[$cont];
            $comanda->save();

            $cont = $cont + 1;
        }

        return response()->json(['success', 'Agendado Correctamente']);
    }
}
