<?php

namespace App\Http\Controllers\Backend;

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

class OrdersController extends Controller
{
    public function index(Request $request)
    {
        $orders_total = Order::count();
        $orders_active = Order::where('status_id', '>', 0)->count();
        $query = Order::query();
        if($request->has('q')) {
            $query->whereHas('user.user_data', function($q) use($request) {
                $q->where('first_name', 'LIKE', "%{$request->q}%")->orWhere('last_name', 'LIKE', "%{$request->q}%");
            });
        }
        if($request->has('status_id')) {
            $query->orWhereIn('status_id', $request->status_id);
        }
        $orders = $query->orderBy('created_at', 'desc')->paginate(10);

        return view('backend.orders.index', [
            'orders' => $orders,
            'orders_total' => $orders_total,
            'orders_active' => $orders_active
        ]);
    }

    public function edit(Order $order)
    {
        $order->load('user.user_data', 'items');

        return view('backend.orders.form', [
            'order' => $order
        ]);
    }

    public function process(Order $order)
    {
        if($order->canProcess()) $order->increment('status_id');

        return back()->with('status', 'El pedido ha sido procesado');
    }
}
