<?php

namespace App\Modules\Libros_electronicos\Reports;

use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithDrawings;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use App\Modules\Libros_electronicos\Models\Compra;
use App\Services\UtilitiesService;
use App\User;

class ComprasExport implements FromView,ShouldAutoSize
{
	protected $data;
	protected $table;
	protected $service;
    public function __construct($data)
    {
        $this->data = $data;
        $this->table = new Compra();
        $this->service = new UtilitiesService();
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function view(): View
    {	
    	$fecha = explode('-', $this->data);
    	$fecha_spanish = $this->service->year_and_month($this->data); 
        $data = $this->set_data_excel($this->table::whereMonth('create_at',$fecha[0])->whereYear('create_at',$fecha[1])->get());
        $user = User::find(Auth::id());
        return view('Libros_electronicos.views.reports.compras', [
            'data' => $data ,
            'fecha_spanish' => $fecha_spanish,
            'mes' => $fecha[0],
            'empresa' => $user
        ]);
    }

    public function set_data_excel($data){
        $data->map(function($c){
            $c->dolares = 0;
            $c->otros =0;
            if ($c->doc_cod == '57') {
                $c->otros = $c->afecto;
            }else if (strtolower($c->forpags) == 'obsequio') {
                $c->otros = $c->inacfecto;
            }else if ($c->anticipo != '0.00') {
                $c->otros = $c->anticipo*-1;
            }
            if ($c->divisa == 'US' OR $c->divisa == 'USD') {
                if ($c->doc_cod == '57') {
                    $c->otros = $c->afecto_cambio;
                }else if (strtolower($c->forpags) == 'obsequio') {
                    $c->otros = $c->inafecto_cambio;
                }else if ($c->anticipo != '0.00') {
                    $c->otros = $c->anticipo*-1;
                }
                $c->dolares = $c->vcompra; 
                $c->afecto = $c->afecto_cambio; 
                $c->inafecto =  $c->inafecto_cambio; 
                $c->vcompra = $c->vcompra; 
                $c->impuesto = $c->impuesto_cambio; 
                $c->totales =  $c->total_cambio; 
                $c->percepcion = $c->percepcion_cambio;
                $c->perdida = ($c->doc_cod == '53') ? $c->total_cambio : 0;
            }
            $c->perdida = ($c->doc_cod == '53') ? $c->total : 0;
        });
        return $data;
    }


}
