/home/dvjjulio/test.istyle.mx/app/Http/Controllers/VentaController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Venta;
use App\Producto;
use App\Cliente;
use App\Comision;
use App\ComisionPago;
use Validator;
use Uuid;
use Auth;
use App\Helper;
use App\Http\Controllers\PremioClienteController;
use App\Http\Controllers\ComisionesController;
use App\Http\Controllers\ComisionPagoController;

class VentaController extends Controller
{
    //
    /* public function index(){
      $clientesI = new Cliente();
      $clientes = $clientesI->Clientes();

      $venta = new Venta();
      
      if(Helper::getRol() == Auth::user()->rol_id){
        $ventas = $venta->ventasAll();
      } else if (Helper::getRolOp() == Auth::user()->rol_id) {
        $ventas = $venta->ventasAll(null, "vacio", null, null, Auth::user()->id);
      } else{
        $ventas = $venta->ventasAll($id = null, Auth::user()->id);
      }
      $cantidad = 0;
      if(isset($ventas)) {
        foreach($ventas as $value) {
          $cantidad += $value->cantidad;
        }
      }
      $productos = Producto::where('status_id',1)->get();

      $redes = new Venta();

      $years = $redes->monthYearVenta();
      // $months = $redes->monthYearVenta(date('Y'));
      $months = [1,2,3,4,5,6,7,8,9,10,11,12];

      $data = ['years'=> $years, 'months'=>$months]; 

    	return view('Catalogos.Venta')->with(compact('ventas','productos','clientes','data', 'cantidad'));
    } */
    public function index($limit = null){
      $clientesI = new Cliente();
      $clientes = $clientesI->Clientes();

      $venta = new Venta();
      
      $year = null;
     $month = null;
     $cliente = null;
     $pagination = null;
     $pagoComision = [];
     if(Helper::getRol() == Auth::user()->rol_id){
      $ventas = $venta->VentasWithLimit($id = null, $limit);
      // $ventasAll = $venta->VentasAll();
      $ventasCount = $venta->VentasCount();
      $ventasPago = $venta->ventasAllPagos();
     }else if (Helper::getRolOp() == Auth::user()->rol_id) {
      $ventas = $venta->VentasWithLimit($id = null, $limit, "vacio",$month, $year, Auth::user()->id);
      // $ventasAll = $venta->VentasAll($id = null,"vacio",$month, $year, Auth::user()->id);
      $ventasCount = $venta->VentasCount($id = null,"vacio",$month, $year, Auth::user()->id);
      $ventasPago = $venta->ventasAllPagos($id = null,"vacio",$month, $year, Auth::user()->id);
     }else{
       $cliente = Auth::user()->id;
       $ventas = $venta->VentasWithLimit($id = null, $limit, $cliente);
      //  $ventasAll = $venta->VentasAll($id = null,$cliente);
       $ventasPago = $venta->ventasAllPagos($id = null,$cliente);
       $ventasCount = $venta->VentasCount($id = null,$cliente);
     }
     if ($ventasCount && $ventasCount[0]->total > 100) {
      $pagination = ceil($ventasCount[0]->total/100);
    }
     $ventaCopy = [];
     $i = 0;
     $j = 0;
     $cantidad = $ventasCount[0]->cantidad ?? 0;
     $countVentas = $ventasCount[0]->total ?? 0;
    /* if ($ventasAll && count($ventasAll) > 0) {
       foreach ($ventasAll as $key => $venta) {
       if ($venta->parent) {
        $cantidad += $venta->cantidad;
        $countVentas++;
       } /* else {
        if($venta->pago != null && $venta->pago != 0) {
          $pagoComision[$j] = ['pago' => $venta->pago, 'nombre' => $venta->nombrePago];
          $j++;
         }
       } */
       /* $countVentas = (count($ventas) -1);
       if ($countVentas >= 2 && $venta->id != $ventas[$countVentas > $key ? $key + 1 : 0]->id) {
        $ventaCopy[$i] = $venta;
        $ventaCopy[$i]->pagoComision = $pagoComision;
        $i++;
        $j = 0;
        $pagoComision = [];
       }*/
     /* } 
    } */
     
     // $comision = new ComisionPago();
     // $comisiones = $comision->getComisionPago($year, $month);

     $productos = Producto::where('status_id',1)->get();

     $redes = new Venta();

     $years = $redes->monthYearVenta();
     $months = $redes->monthYearVenta(2021);

     $data = ['years'=> $years, 'months'=>$months];

    	return view('Catalogos.Venta')->with(compact('ventas','productos','clientes','data', 'cantidad', 'ventasPago', 'pagination', 'countVentas'));
    } 
   public function getVentas(Request $request){
    $data = $request->all();
      $limit = $data['limit'] ?? null;
     $clientesI = new Cliente();
     $clientes = $clientesI->Clientes();
     $pagination = null;

     $venta = new Venta();
    
     $year = $data['year'] ?? null;
     $month = $data['month'] ?? null;
     $pagoComision = [];
     if(Helper::getRol() == Auth::user()->rol_id){
       $cliente = $data['cliente'];
       $ventasCount = $venta->VentasCount($id = null,$cliente,$month, $year);
       $ventas = $venta->VentasWithLimit($id = null, $limit,$cliente,$month, $year);
      //  $ventasAll = $venta->ventasAll($id = null,$cliente, $month, $year);
      $ventasPago = $venta->ventasAllPagos($id = null, $cliente, $month, $year);
     }else if (Helper::getRolOp() == Auth::user()->rol_id) {
      $cliente = $data['cliente'];
      $ventas = $venta->VentasWithLimit($id = null, $limit, $cliente,$month, $year, Auth::user()->id);
      // $ventasAll = $venta->ventasAll($id = null,$cliente,$month, $year, Auth::user()->id);
      $ventasCount = $venta->VentasCount($id = null,$cliente,$month, $year, Auth::user()->id);
      $ventas = $venta->ventasAllPagos($id = null,$cliente,$month, $year, Auth::user()->id);
     }else{
       $cliente = Auth::user()->id;
       $ventas = $venta->VentasWithLimit($id = null, $limit, $cliente,$month, $year);
      //  $ventasAll = $venta->ventasAll($id = null,$cliente,$month, $year);
       $ventasCount = $venta->VentasCount($id = null,$cliente,$month, $year);
       $ventas = $venta->ventasAllPagos($id = null,$cliente,$month, $year);
     }
     if ($ventasCount && $ventasCount[0]->total > 100) {
      $pagination = ceil($ventasCount[0]->total/100);
      }
     $ventaCopy = [];
     $i = 0;
     $j = 0;
     $cantidad = $ventasCount[0]->cantidad ?? 0;
     $countVentas = $ventasCount[0]->total ?? 0;
     /* if (isset($ventasAll) && count($ventasAll) > 0) {
      foreach ($ventasAll as $key => $venta) {
        if ($venta->parent) {
          $cantidad += $venta->cantidad;
          $countVentas++;
        } /* else {
          if($venta->pago != null && $venta->pago != 0) {
            $pagoComision[$j] = ['pago' => $venta->pago, 'nombre' => $venta->nombrePago];
            $j++;
          }
        } */
        /* $countVentas = (count($ventas) -1);
        if ($countVentas >= 2 && $venta->id != $ventas[$countVentas > $key ? $key + 1 : 0]->id) {
          $ventaCopy[$i] = $venta;
          $ventaCopy[$i]->pagoComision = $pagoComision;
          $i++;
          $j = 0;
          $pagoComision = [];
        }*/
     /* }
    } */
     // $comision = new ComisionPago();
     // $comisiones = $comision->getComisionPago($year, $month);

     $productos = Producto::where('status_id',1)->get();

     $redes = new Venta();

     $years = $redes->monthYearVenta();
     $months = $redes->monthYearVenta(2021);

     $data = ['years'=> $years, 'months'=>$months];

     return view('Catalogos.sectionVentaTable')->with(compact('ventas','productos','clientes','data', 'cantidad', 'ventasPago', 'pagination', 'countVentas'));
   }

   public function checkSomeComisiones($data) {
    $comision = new Comision();
    $redes = new Venta();
    $date = \DateTime::createFromFormat("Y-m-d", $data['fecha_venta']);
    for ($i = 1; $i <= 3; $i++) {
      if ($data['cliente_comision_'.$i] != 'vacio' && $data['cliente_comision_'.$i] != '' && $data['cliente_comision_'.$i] != null) {
        // $comisionResult = $comision->existComisionCantidad($data['id'], $data['cliente_comision_'.$i], $data['cantidad_comision_'.$i], $date->format('Y'), $date->format('m'));
        $comisionAvilable = $redes->Get_3_Months($data['cliente_comision_'.$i], $date->format('Y'), $date->format('m'));
        $clienteData = Cliente::find($data['cliente_comision_'.$i]);
        if($data['cantidad_comision_'.$i] > $comisionAvilable[0]->comision) {
          return ['status' => false,'message'=> 'El cliente '. $clienteData->nombre.' '.$clienteData->ape_p.' no dispone de comisiones'];
        }
      }
    }
    return ['status' => true,'message'=> 'ok'];
   }

   public function guardar(Request $request){
      $data = $request->all();

      $checkComisiones = $this->checkSomeComisiones($data);
      if(!$checkComisiones['status']) return response()->json(['status' => $checkComisiones['status'], 'message' => $checkComisiones['message']]);

      $premioCliente = new PremioClienteController();

    	$validacion = Validator::make($data,
    	 array(
    	 	'vendedor' => 'required',
        'venta' => 'required',
        'fecha_venta' => 'required',
    	 	),
    	 array(
    	 	'vendedor.required' => 'El vendedor es obligatorio',
        'venta.required' => 'Debe haber productos en la venta',
        'fecha_venta.required' => 'Se debe seleccionar una fecha',
        )
    	);


  if($validacion->fails()){
  	return response()->json(['status'=>false,'message'=>$validacion->messages()]);
  }

  	if($data['id']=="0"){
      foreach ($data['venta'] as $key => $value) {
        if($value['cantidad'] == "" || $value['cantidad']== 0){
          return response()->json(['status'=>false,'message'=>'Error en una cantidad, esta vacia o en 0']);
        }else if($value['producto'] == ""){
          return response()->json(['status'=>false,'message'=>'Error en un producto, esta vacio']);
        }else{
          $venta = new Venta();
      		$venta->id = Uuid::generate()->string;
          $venta->cliente_id = $data['vendedor'];
          $venta->fecha_venta = $data['fecha_venta'];
          $venta->comentario = $data['comentario'];
          $venta->cantidad = $value['cantidad'];
          $venta->producto_id = $value['producto'];
          $venta->total = $this->getTotal($value['cantidad'],$value['producto']);
          $venta->registro_id = Auth::user()->id;

          if(Helper::getRol() == Auth::user()->rol_id) {
            $venta->approved = 1;
            $venta->approved_by = Auth::user()->id;
          }

          if(!$venta->save()){
            return response()->json(['status' => false,'message'=>'Error al registrar la venta']);
          }
        }
      }

  		$mesage = "La venta ha sido creada exitosamente";
  	}else{
      foreach ($data['venta'] as $key => $value) {
        if($value['cantidad'] == "" || $value['cantidad']== 0){
          return response()->json(['status'=>false,'message'=>'Error en una cantidad, esta vacia o en 0']);
        }else if($value['producto'] == ""){
          return response()->json(['status'=>false,'message'=>'Error en un producto, esta vacio']);
        }else{
          $venta = Venta::find($data['id']);
          $venta->cliente_id = $data['vendedor'];
          $venta->comentario = $data['comentario'];
          $venta->fecha_venta = $data['fecha_venta'];
          $venta->cantidad = $value['cantidad'];
          $venta->producto_id = $value['producto'];
          $venta->total = $this->getTotal($value['cantidad'],$value['producto']);
          $venta->registro_id = Auth::user()->id;

          if(!$venta->save()){
            return response()->json(['status' => false,'message'=>'Error al registrar la venta']);
          }
        }
      }
  		$mesage = "La venta ha sido actualizada correctamente";
    }

    $saveComision = $this->saveComisionPago($data, $venta->id);
    if(!$saveComision['status']) return response()->json(['status' => $saveComision['status'], 'message' => $saveComision['message']]);

    // Arrglar premios
    //$premioCliente->clientePremio();
	  return response()->json(['status' => true, 'message' => $mesage, 'data' => $data]);

  }

  public function saveComisionPago($data, $venta_id) {
    // $comisionPago = new ComisionPagoController();
    $comisiones = new ComisionesController();
    for ($i = 1; $i <= 3; $i++) {
      if ($data['cliente_comision_'.$i] != 'vacio' && $data['cliente_comision_'.$i] != '' && $data['cliente_comision_'.$i] != null) {
          $pago = $comisiones->updateGastoComision($data['cliente_comision_'.$i], $venta_id, $data['cantidad_comision_'.$i]);
        // return $pago = $comisionPago->guardar($data['cliente_comision_'.$i], $venta_id, $data['cantidad_comision_'.$i]);
      if (!$pago['status']) {
        return ['status' => false, 'message' => 'Algo fallo en el guardado de Pago', 'data' => $data];
      }  
     }
    }
    return ['status' => true, 'message' => 'ok', 'data' => $data];
  }

  public function getTotal($cantidad, $producto){
    $productos = Producto::find($producto);
    return $productos->costo_mx * $cantidad;
  }

  public function update(Request $request){
  	$id = $request->input('id');
    $venta = new Venta();
    $comisionPago = ComisionPago::select('comision_pago.id', 'comision_pago.venta_id', 'comision_pago.cliente_id',
                                    'comision_pago.cantidad','cliente.registro', 'cliente.ape_p', 'cliente.nombre', 'cliente.ape_m')
                                  ->join('cliente', 'cliente.id', 'comision_pago.cliente_id')
                                  ->where('venta_id', $id)->where('comision_pago.status_id', 1)->get();
    $ventas = $venta->ventasAll($id);
    return ['comisionPago' => $comisionPago, 'ventas' => $ventas];
  	return Venta::find($id);
  }

  public function delete(Request $request){
    $comisionPago = new ComisionPagoController();
  	$venta = Venta::Find($request->input('id'));
  	$venta->status_id=0;
    $venta->registro_id = Auth::user()->id;
    if (!$comisionPago->deleteComisionFromVenta($venta->id)) return response()->json(['status'=>false,'message'=>'Error al eliminar registro en comisiones']);
  	if ($venta->save()){
  		return response()->json(['status'=>true,'message'=>'Registro eliminado correctamente']);
  	}else{
  		return response()->json(['status'=>false,'message'=>'Error al eliminar registro']);
  	}
  }

  public function section(Request $request){
    $count = $request->input('count');
    $productos = Producto::where('status_id',1)->get();
    return view('Catalogos.sectionVenta')->with(compact('productos','count'));
  }

  public function approve(Request $request) {
    $venta_id = $request->input('venta_id');

    $venta = Venta::find($venta_id);

    $venta->approved = 1;
    $venta->approved_by = Auth::user()->id;

    if ($venta->save()){
  		return response()->json(['status'=>true,'message'=>'Registro aprovado correctamente']);
  	}else{
  		return response()->json(['status'=>false,'message'=>'Error al aprovar registro']);
  	}

  }
}