<?php

namespace App\Modules\Libros_electronicos\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Controller;
use App\Services\UtilitiesService;
use App\Modules\Libros_electronicos\Models\Rphonorario;
use App\Modules\Libros_electronicos\Models\Rphonorarios_linea;
use App\Modules\Libros_electronicos\Reports\RphonorariosExport;
use App\Modules\Catalogo\Models\Plan_cuenta;
use App\Modules\Catalogo\Models\Ccosto;
use App\Modules\Utilitarios\Models\Files_contable;
use Yajra\Datatables\Datatables;
use Maatwebsite\Excel\Facades\Excel;
use Mpdf\Mpdf;
use Session;
use DB;
class RphonorariosController extends Controller
{
    protected $table;
    protected $table_lineas;
    protected $table_u;
    protected $table_p;
    protected $table_c;
    protected $files;
    function __construct(){
        $this->table  = new Rphonorario();
        $this->table_lineas  = new Rphonorarios_linea();
        $this->table_u = new UtilitiesService();
        $this->table_p = new Plan_cuenta();
        $this->table_c = new Ccosto();
        $this->files = new Files_contable();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        return view('Libros_electronicos.views.rphonorarios')->with('data');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('Libros_electronicos.views.add.rphonorarios')->with('complet',$this->table->get_all());
    }
    /**
     * Obtener datos datatable
     *
     * @return data 
    */
    public function getTable($fecha){
        $this->table->fec_my = $fecha;
        $ssf = explode('/', $fecha);
        session(['fecha_compra' =>$ssf[1].'-'.$ssf[0].'-'.date('d')]);
        $table = Datatables::of($this->table->relation_shop());
        $table->addColumn('action', function($row){
            $url = url()->current().'/'.$row['id'];
            return view('layouts.buttons.buttons-dinamyc',['buttons'=> array(
                array('tipe'=>'edit',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url.'/edit',
                      'class'=>" btn btn-sm btn-primary",
                      'icon'=>"icon-compose"
                ),
                array('tipe'=>'delete',
                      'id_row'=>$row['id'],
                      'modal'=>'no',
                      'url'=>$url.'&honorario',
                      'class'=>"btn btn-sm btn-danger fn_delete",
                      'icon'=>"icon-trash"
                )
            )]);
        })->addColumn('documento', function($row){
            if (!empty($row->tipdocs)) {
                $docs = $row['doc_sig'].'-'.$row['serie'].'-'.$row['numero'];
            }else{
                $docs = '-'.$row['serie'].'-'.$row['numero'];
            }
            return $docs;
        })->rawColumns(['action','documento']);
        return $table->make(true);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {   
        if ($request->has('action')) {
            $data = $request->all();
            switch ($data['action']) {
                case 'showtable':
                    $fecha = $request->has('search_fecha') ? $request->input('search_fecha') : date('m/Y');
                    return $this->getTable($fecha);
                break;
                case 'change_number':
                    $fech = explode('-', $request->input('fecha'));
                    $num = $this->table::whereMonth('create_at',$fech[1])->whereYear('create_at',$fech[0])->orderBy('codigo_num','DESC')->first();
                    if (!empty($num)) {
                        return $num->codigo_num;
                    }else{
                        return 0;
                    }
                break;
                case 'add':
                    $validator = Validator::make($request->all(),[
                        'codigo_num' => 'required',
                        'nombre' => 'required',
                        'numero_identidad' => 'required',
                        'tipdocs_id' => 'required',
                        'serie' => 'required',
                        'numero' => 'required',
                        'divisa' => 'required',
                        'dias' => 'required',
                        'fec_emision' => 'required',
                        'fec_vencimiento' => 'required',
                        'codigo.*'=>'required',
                        'cantidad.*'=>'required',
                        'um.*'=>'required',
                        'precio.*'=>'required',
                        'cuenta.*'=>'required',
                        'dolares.*'=>'required',
                        'debe.*'=>'required',
                        'haber.*'=>'required',
                        'forpags'=>'required',
                    ]);

                   if ($validator->fails()) {
                       return response()->json(['error'=>$validator->errors()->all()]);

                    }else{
                        $this->table->fill($request->except(['idfile','id_venta','action']))->save();
                        $this->table->save_cuentas();
                        $request->session()->flash('create', 'Registro agregado con exito, puede adicionar sus conceptos y articulos a continuacion!');
                        return response()->json(['success'=>'Compra agregado con exito', 'noreload'=>'noreload','url'=>url('rphonorarios/'.$this->table->id.'/edit')]);
                    }
                break;
                case 'pdf':
                    $this->generatePdf($request->input('id'));
                break;
                case 'lock':
                    $datos = $request->all();
                    $data = $this->table::find($datos['id']);
                    if (!empty($data)) {
                        $status = ($data['status'] == 0) ?  1 : 0;
                        $data->status = $status;
                        $data->save(); 
                        return response()->json(['success'=>$status]);
                    }
                break;
                case 'getlineas':
                    $this->table->rphonorarios_id = $request->input('id');
                    $lineas = $this->table->relation_line();
                    return response()->json(['date'=>$lineas]);
                break;
                case 'get_item_c':
                    $compra = $this->table::find($request->input('id'));
                    return $compra;
                break;
            }
        }else{
            return response()->json(['error'=>'No existe ningun token por favor no borre nuesto codigo html']);
        }
    }
    /**
     * Generar PDF
     *
     */
    public function generatePdf($id){

        $mpdf=new Mpdf(); 
        $this->table->id_compra =  $id;
        $compra =  $this->table->get_by_id();
        $html = view('Libros_electronicos.views.pdf')->with('compra',$compra)->render();
        $mpdf->AddPage('P','A4','','','',20,15,30,25,10,10);
        $mpdf->SetProtection(array('print'));

        $mpdf->SetTitle("Acme Trading Co. - Invoice");

        $mpdf->SetAuthor("Acme Trading Co.");

        $mpdf->SetWatermarkText("Paid");

        $mpdf->showWatermarkText = true;

        $mpdf->watermark_font = 'DejaVuSansCondensed';

        $mpdf->watermarkTextAlpha = 0.1;

        $mpdf->SetDisplayMode('fullpage');

        $mpdf->WriteHTML($html);

        $mpdf->Output();
        exit;
    }
    /**
     * Generar Excel
     *
    */
    public function Excel_export($fecha){
        if ($fecha == 'actually'):
            $fecha = date('m-Y');
        endif;
        return Excel::download(new RphonorariosExport($fecha), 'Rphonorarios'.$fecha.'.xlsx');
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $this->table->id_venta =  $id;
        $compra =  $this->table->get_by_id();
        return view('Libros_electronicos.views.view')->with('compra',$compra);
    }
    /**
     * Modals para edicion de concepto y articulos
     *
     * @param  int  $id
     * @return views for edits
    */
    public function lineas_add_edit(Request $request){
        $cuentas = $this->table_p::all();
        $ccostos = $this->table_c::all();
        if ($request->has('action')) {
            switch ($request->input('action')) {
                case 'createModal':
                    $tipo = $request->input('modal'); $id = $request->input('id_compra');
                    $identidad = $request->input('identida');
                    return view('Libros_electronicos.views.add.'.$tipo)
                    ->with('complet',
                          ['cuentas'=>$cuentas,
                          'ccostos'=>$ccostos
                          ])
                    ->with('head',
                          ['id'=>$id,
                           'tipe_id'=>'ventas_id',
                           'identidad'=>$identidad,
                           'url'=> url('ventas'),
                           'tipe' => 'ventas'
                          ]);
                break;
                case 'updateModal':
                    $lineas = $this->table_lineas::find($request->input('id')); 
                    //$id = $request->input('id_compra');
                    $identidad = $request->input('identida');
                    if (!empty($lineas)) {
                        return view('Libros_electronicos.views.edit.'.$lineas->tipe_linea)
                        ->with('data',
                               ['linea'=>$lineas,
                               'cuentas'=>$cuentas,
                               'ccostos'=>$ccostos
                               ])
                        ->with('head',
                                [
                                'identidad'=>$identidad,
                                'url'=>url('ventas/'.$lineas->id)
                                ]);
                    }
                break;
                case 'entidad_fac':
                   $this->table->identidad = $request->input('identidad');
                   $this->table->id = $request->input('id_venta');
                   $search = $this->table->get_by_ruc();
                   $venta = $this->table::find($request->input('id_venta'));
                   return view('Libros_electronicos.views.utilitarios.search_f_relacional')->with('data',['search'=>$search,'contable'=>$venta]);
                break;
            }
        }
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $cabecera = $this->table::find($id);
        $detalles = $this->table::where('rphonorarios_id',$id);
        $files = $this->files::where('tipe_modulo','ventas')->where('id_files',$id)->get();
        if (!empty($cabecera)) {
            return view('Libros_electronicos.views.edit.rphonorarios')
            ->with('data',['cabecera'=>$cabecera,'detalles'=>$detalles])
            ->with('complet',$this->table->get_all())
            ->with('files',$files);
        } 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if ($request->has('action')) {
           $data = $request->all();
           switch ($data['action']) {
               case 'update':
                    $data = $this->table::find($id);
                    if (!empty($data)) {
                        $data->fill($request->except(['action','id_d','idfile']))->save();
                        $this->table->tipdocs_id = $data['tipdocs_id'];
                        $this->table->id = $id;
                        $this->table->save_cuentas();
                        return response()->json(['success'=>'Registro actualizado con exito']);
                    }
               break;
               case 'updateconcepto':
                    $linea = $this->table_lineas::find($id);
                    if (!empty($linea)) {
                        unset($data['action'],$data['iduser']);
                        $data['afecto'] = ($request->has('afecto')) ? $data['afecto'] : 'off';
                        $data['igvpercent'] = (!empty($data['igvpercent'])) ? $data['igvpercent'] : 0;
                        $linea->fill($data)->save();
                        return response()->json(['success'=>'Registro actualizado con exito']);
                    }
               break;
               case 'updatearticulo':
                    $linea = $this->table_lineas::find($id);
                    if (!empty($linea)) {
                        unset($data['action'],$data['iduser']);
                        $data['igvpercent'] = (!empty($data['igvpercent'])) ? $data['igvpercent'] : 0;
                        $linea->fill($data)->save();
                        return response()->json(['success'=>'Registro actualizado con exito']);
                    }
                break;
               
               default:
                   # code...
               break;
           }
        }
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
       $datos = explode('&', $id);
       switch ($datos[1]) {
           case 'honorario':
               $data = $this->table::find($datos[0]);
               if (!empty($data)) {
                   $data->delete();
                   if (is_dir(base_path().'/public/storage/Honorario'.$datos[0])) {
                        Storage::disk('public_uploads')->deleteDirectory('Honorario'.$datos[0]);
                    }
                   $this->table_lineas::where('rphonorarios_id', '=', $datos[0])->delete();
                   $this->files::where('tipe_modulo','Honorario')->where('id_files', '=', $datos[0])->delete();
                   return response()->json(['success'=>'Registro eliminado con exito']);
               }
            break;
            case 'linea':
              $data = $this->table_lineas::find($datos[0]);
              if (!empty($data)) {
                $data->delete();
                return response()->json(['success'=>'Registro eliminado con exito']);
              }
            break;
           
           default:
               # code...
            break;
       }
    }
}
