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

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Fpdf;
use App\Cliente;
use App\Venta;
use App\ISR;
use App\Helper;
use App\Nivel;
use App\Pais;
use NumeroALetras;
class ReportController extends Controller
{
    //
    public function newSheet(){
      $pdf = new Fpdf();
      $pdf::AddPage('P','Legal');
      $pdf::Image(__DIR__.'/../../../public/img/reporte/comisiones.jpeg',0,0,216,'JPEG');
      return $pdf;
    }
    public function titleRed($pdf, $data){
      $pdf::SetFont('Arial','',15);
      $pdf::SetY(55);
      $pdf::Cell(130,4,utf8_decode("Nombre: ".$data['cliente'][0]->nombre." ".$data['cliente'][0]->ape_p." ".$data['cliente'][0]->ape_m),0,0);
      $pdf::SetY(62);
      $pdf::Cell(130,4,utf8_decode("Dirección: ".$data['cliente'][0]->calle." ".$data['cliente'][0]->numero.", ".$data['cliente'][0]->colonia),0,0);
      $pdf::SetY(69);
      $pdf::Cell(110,4,utf8_decode("Población: ".$data['cliente'][0]->pais.", ".$data['cliente'][0]->delegacion.", ".$data['cliente'][0]->estado),0,0);
      $pdf::Cell(30,4,utf8_decode("Telefono: ".$data['cliente'][0]->lada." ".$data['cliente'][0]->tel),0,0);

      return $pdf;
    }

    public function red($id, $year, $month){
      $pdf = $this->newSheet();
      $data = $this->redInfo($id, $year, $month);

      $pdf = $this->titleRed($pdf,$data);

      $pdf::SetFont('Times','I',20);
      $pdf::SetTextColor(0,0,0,1);
      $pdf::SetXY(160,15);
      $pdf::Cell(30,6,"Activos ",0,0,'C');
      $pdf::SetXY(160,25);
      $pdf::Cell(30,6,Helper::month($month),0,0,'C');
      $pdf::SetXY(160,33);
      $pdf::Cell(30,6,$year,0,0,'C');

      $pdf::SetFont('Arial','B',17);
      $pdf::SetTextColor(255,255,255,1);
      $pdf::SetY(75);
      $pdf::Cell(30,6,"Nivel",0,0,'C');
      $pdf::Cell(130,6,"Nombre",0,0,'C');
      $pdf::Cell(40,6,"Importe",0,0,'C');


      $pdf::SetY(78);
      $cajas = 0;
      foreach ($data['red'] as $key => $value) {
        //return $value;
        foreach ($value as $key => $red) {
          if($red->comision){
            $cajas++;
            $pdf::SetFont('Arial','',14);
            $pdf::SetY($pdf::GetY()+5);
            $pdf::SetTextColor(0,0,0);
            $pdf::Cell(30,4,$red->nivel,0,0,'C');
            $pdf::Cell(130,4,utf8_decode($red->nombre." ".$red->apellidos),0,0,'C');
            $pdf::Cell(40,4,"$".number_format(($red->total < 4000 | !$red->comisiona)? 0 : $red->comision,2),0,0,'C');

            if($pdf::GetY() >= 310){

              $pdf = $this->newSheet();
              $pdf = $this->titleRed($pdf,$data);
              $pdf::SetY(78);
            }
          }
        }
      }

      $pdf::SetY(326);
      $pdf::SetFont('Arial','',19);
      $pdf::SetTextColor(181,0,0);
      $pdf::Cell(30,6,$cajas,0,0,'C');

      $pdf::SetFont('Arial','',17);
      $pdf::SetTextColor(0,0,0);
      $pdf::Cell(90,6,"Cajas Calificadas",0,0);

      $pdf::SetFont('Arial','',15);
      $pdf::SetXY(142,317);
      $pdf::Cell(30,6,"Sub-Total: ",0,0,'R');
      $pdf::Cell(30,6,"$".number_format($data['comision'],2),0,0,'L');
      $pdf::SetXY(142,323);
      $pdf::Cell(30,6,"ISR: ",0,0,'R');
      if(isset($data['isr'])){
        $isr = number_format(($data['comision'] * ($data['isr'][0]->porcentaje/100)),2);
      }else{
        $isr = 0.00;
      }
      $pdf::Cell(30,6,"$".$isr,0,0,'L');
      $pdf::SetXY(142,329);
      $pdf::Cell(30,6,"Total: ",0,0,'R');
      if(isset($data['isr'])){
        $calc_isr = number_format($data['comision']-(($data['comision'] * ($data['isr'][0]->porcentaje/100))),2);
      }else{
        $calc_isr = 0.00;
      }
      $pdf::Cell(30,6,"$".$calc_isr,0,0,'L');

      $pdf::SetXY(60,317);
      $pdf::SetFont('Arial','',10);
      $pdf::SetTextColor(181,0,0);
      $pdf::Cell(30,6,utf8_decode($data['message']),0,0,'C');

      $pdf::Output('I','Activos.pdf');
      exit;
    }

    public function redInfo($id, $year, $month){
      $ids = '"'.$id.'"';

      $clientesI = new Cliente();
      $cliente = $clientesI->Clientes($id);

      $clientePais = 'Mexico';
      if(isset($cliente[0]->pais)) $clientePais = $cliente[0]->pais;
      //$year = $data['year'];
      //$month = $data['month'];

      $redes = new Venta();
      $red = [];

      $message = "";
      $total = 0;
      $comision = 0;
      $red_size = 0;
      $controlLessFront = [];
      $redController = new RedController();
      $compra = $redes->cliente_compra($id, $year, $month);
      $frontales = $redController->afterTen($id, $year, $month);
      for($i = 1; $i<= 4; $i++){
         $red_first = $redes->red_first($ids,$i,$month,$year, $clientePais);
        if(isset($red_first)){
          $ids = $redController->get_ids($red_first);
          $red[$i] = $red_first;
          foreach($red_first as $val){
            if($val->total >= 4000 && $val->comisiona){
              $comision += $val->comision;
            }
            $red_size++;
            $total += $val->total;
          }
        }else{
            break;
        }
      }
      // for($i = 1; $i<= 4; $i++){
      //    $red_first = $redes->red_first($ids,$i,$month,$year, $clientePais);
      //   if(isset($red_first)){
      //     $ids = $redController->get_ids($red_first);
      //     $red[$i] = $red_first;
      //     foreach($red_first as $val){
      //       if(($val->total < 4000 || $val->total >= 10000) | !$val->comisiona){
      //         $comision += 0;
      //       }else{
      //         $comision += $val->comision;
      //       }
      //       $red_size++;
      //       $total += $val->total;
      //     }
      //   }else{
      //       break;
      //   }
      // }
      if($comision >= 400000 || $cliente[0]->nivel == 2){
        $redController->checkLevel($cliente[0]->id, 2);

        $frontales = $redController->afterTen($id,$year,$month, $clientePais);
      if($frontales < 10){
        $message = "Necesitas tus 10 frontales con venta para tus activos";
        // $comision = 0;
        $comisionType = Helper::getComisionCountry($cliente[0]->pais);
        $firstLevel = Nivel::where('nivel', 'Primer')->first();
        $comision = $frontales * $firstLevel->$comisionType;
        $ids = '"'.$id.'"';
        // $year = $data['year'];
        // $month = $data['month'];
        $front = 1;
        for($i = 1; $i<= 2; $i++){
           $red_first = $redes->red_first($ids,$i,$month,$year, $clientePais);
          if(isset($red_first)){
            $ids = $redController->get_ids($red_first);
            foreach($red_first as $val){
              if($val->total >= 4000){
                if($front <= $frontales){
                  // $comision += $val->comision;
                  $secondLevel = Nivel::where('nivel', 'Segundo')->first();
                  $comision += $val->nivel === 'Segundo' ? $secondLevel->$comisionType : 0;
                  $front++;
                }
              }
            }
            $front = 1;
          }
        }
      }

    }else if(($comision >= 10000 && $comision <= 400000) || $cliente[0]->nivel == 1){
        $frontales = $redController->afterTen($id,$year,$month);
        if($frontales < 5){
          $message = "Necesitas tus 5 frontales con venta para tus activos";
          // $comision = 0;
          $comisionType = Helper::getComisionCountry($cliente[0]->pais);
          $firstLevel = Nivel::where('nivel', 'Primer')->first();
          $comision = $frontales * $firstLevel->$comisionType;
          $ids = '"'.$id.'"';
          $front = 1;
          for($i = 1; $i<= 2; $i++){
             $red_first = $redes->red_first($ids,$i,$month,$year, $clientePais);
            if(isset($red_first)){
              $ids = $redController->get_ids($red_first);
              foreach($red_first as $val){
                if($val->total >= 4000){
                  if($front <= $frontales){
                    // $comision += $val->comision;
                    $secondLevel = Nivel::where('nivel', 'Segundo')->first();
                    $comision += $val->nivel === 'Segundo' ? $secondLevel->$comisionType : 0;
                    $front++;
                  }
                }
              }
              $front = 1;
            }
          }
        }

      }

      if(!$compra) $message = 'NO TIENE DERECHO A ACTIVOS!';

      $isr = new ISR();
      $isr_porcentaje = $isr->get_isr($comision);

      return $data = ['total'=>$total,'comision'=>$comision, 'red_size'=>$red_size, 'isr'=>$isr_porcentaje, 'cliente'=>$cliente, 'red'=>$red, 'message'=>$message];
    }


    public function newSheetVenta(){
      $pdf = new Fpdf();
      $pdf::AddPage('P',"Letter");
      return $pdf;
    }

    public function venta($id,$id2 = null){
      $ventas = new Venta();
      $venta = $ventas->ventasAll($id);
      $pdf = $this->newSheetVenta();

      $pdf::SetFont('Arial','',13);
      $pdf::SetXY(179,18);
      $fecha = explode("-",$venta[0]->fecha_venta);
      $pdf::Cell(11,4,$fecha[2],0,0,'C');
      $pdf::Cell(15,4,$fecha[1],0,0,'C');
      $pdf::Cell(11,4,$fecha[0],0,0,'C');

      $pdf::SetXY(30,27);
      $pdf::Cell(130,4,ucwords(strtolower(utf8_decode($venta[0]->cliente." ".$venta[0]->ape_p." ".$venta[0]->ape_m)))." ".$venta[0]->lada." ".$venta[0]->tel,0,0);
      $pdf::SetXY(30,32.5);
      $pdf::Cell(165,4,ucwords(strtolower(utf8_decode($venta[0]->calle." ".$venta[0]->numero.", ".$venta[0]->colonia))),0,0);
      $pdf::Cell(20,4,utf8_decode($venta[0]->cp),0,0);
      $pdf::SetXY(30,38);
      $pdf::Cell(130,4,ucwords(strtolower(utf8_decode($venta[0]->delegacion.", ".$venta[0]->estado))),0,0);
      $pdf::SetXY(10,55);
      $pdf::SetFont('Arial','',13);


      $pdf::Cell(20,4,ucwords(strtolower(utf8_decode($venta[0]->cantidad))),0,0);
      $pdf::Cell(130,4,ucwords(strtolower(utf8_decode($venta[0]->descripcion))),0,0);
      $pdf::Cell(30,4,"$".number_format($venta[0]->costo_mx,2),0,0);
      $pdf::Cell(30,4,"$".number_format($venta[0]->total,2),0,0);

      if (strpos($venta[0]->comentario,"|")){
        $comentObj = explode("|",$venta[0]->comentario);
        $y = 61;
        foreach($comentObj as $val){
          $pdf::SetXY(35,$y);
          $pdf::Cell(110,4,utf8_decode($val),0,0);
          $y += 5;
        }
      }else{
        $pdf::SetXY(35,61);
        $pdf::Cell(110,4,utf8_decode($venta[0]->comentario),0,0);
      }

      if($id2 != null){
        $venta2 = $ventas->ventasAll($id2);
        $pdf::SetXY(10,90);
        $pdf::Cell(20,4,ucwords(strtolower(utf8_decode($venta2[0]->cantidad))),0,0);
        $pdf::Cell(130,4,ucwords(strtolower(utf8_decode($venta2[0]->descripcion))),0,0);
        $pdf::Cell(30,4,"$".number_format($venta2[0]->costo,2),0,0);
        $pdf::Cell(30,4,"$".number_format($venta2[0]->total,2),0,0);

        if (strpos($venta2[0]->comentario,"|")){
          $comentObj = explode("|",$venta2[0]->comentario);
          $y = 96;
          foreach($comentObj as $val){
            $pdf::SetXY(35,$y);
            $pdf::Cell(110,4,utf8_decode($val),0,0);
            $y += 5;
          }
        }else{
          $pdf::SetXY(35,96);
          $pdf::Cell(110,4,utf8_decode($venta2[0]->comentario),0,0);
        }
      }


      $pdf::SetXY(25,123);
      $pdf::SetFont('Arial','',13);
      $pdf::Cell(165,4,ucwords(strtolower(NumeroALetras::convertir($venta[0]->total)))." pesos MN",0,0);
      $pdf::Cell(30,4,"$".number_format($venta[0]->total,2),0,0);

      $pdf::Output('I','Activos.pdf');
      exit;
      //return $venta;
    }
}