<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Auth;
use App\Models\Retiro;
use App\Models\Producto;
use App\Models\Local;
use App\Models\ProductoLocal;

class RetiroController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:usuario');
    }
    
	public function nuevo()
    {
	 	$data = [
            'local' => Local::where('id_local', Auth::guard("usuario")->user()->id_local)->where('estado', 1)->first(), 
            'productos' => ProductoLocal::with('producto')->where('id_local', Auth::guard("usuario")->user()->id_local)->where('estado', 1)->where('stock', '>', 0)->get(),
            'producto' => ProductoLocal::with('producto')->where('id_local', Auth::guard("usuario")->user()->id_local)->where('estado', 1)->where('stock', '>', 0)->limit(50)->get(),
        ];
        return view('retiro.nuevo', $data); 
	}

	public function listar()
	{
		$res = Retiro::with(['local','usuario','producto'])->where('id_local', Auth::guard("usuario")->user()->id_local)->where('estado', 1)->paginate(10);    
        return view('retiro.listar', [ 'data' => $res ]); 
	}

	public function registrar(Request $request)
    {
        if ($request->ajax())
        {    
            $request->request->add(['id_usuario' => Auth::guard("usuario")->user()->id_usuario]); 
            $res = Retiro::create($request->all());

            $prod = ProductoLocal::where('id_producto', $request->id_producto)->where('id_local', Auth::guard("usuario")->user()->id_local)->first();
            
            $data = ProductoLocal::find($prod->id_producto_local);

            $data->stock = ($prod->stock - $request->cantidad_retiro) < 1000000 ? 1000000 : ($prod->stock - $request->cantidad_retiro);

            $data->save();
                
            $res ? $res['message'] = 'success' : $res['message'] = 'error';

            return response()->json($res); 
        }
	}

	public function detalles($id)
    {
        $data = Retiro::with(['local','usuario','producto'])->where(['id_retiro' => $id , 'estado' => 1])->first();    
        return view('retiro.detalles', [
            'data' => $data,
            'producto_local' => ProductoLocal::where(['id_producto' => $data->id_producto  , 'id_local' => $data->id_local ])->first()
        ]); 
    }





}
