<?php

namespace App\Http\Controllers;

//change the request class if needed
use Illuminate\Http\Request as Request;

use App\Models\Truck\InvoiceProcurement as Entity;

use App\Http\Resources\JsonResource;
use App\Models\Truck\Company;
use App\Models\Truck\CompanyProcurement;
use App\Models\Truck\Driver;
use App\Models\Truck\Truck;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Auth;

class TruckInvoicesProcurementController extends Controller 
{
    protected $request;
    
    public function __construct(Request $request)
    {
        $this->request = $request;

    }
    
    public function index()
    {   
        $sum = $this->getSummary();

        return view('truck.invoices_procurement.index', ['sum' => $sum]);
    }
    
    /*
     * Yajrabox datatables metod
     */
    public function datatable()
    {
        $query = Entity::query()->where('id', '>', 0)->orderBy('created_at', 'desc');

        return datatables($query)
            ->addColumn('actions', function ($entity) {
                return view('truck.invoices_procurement.partials.table.actions', 
                            ['entity' => $entity]);
            })->editColumn('currencys', function ($entity) {
                return  $entity->currency;
            })->editColumn('price', function ($entity) {
                return $entity->price .' '. $entity->currency;
            })->editColumn('company', function ($entity) {
                $company = CompanyProcurement::withTrashed()->where('id', $entity->company)->first();    
                return $company['name'];  
            })->editColumn('date_start',function($entity){
                $date = Carbon::parse($entity->date_start);
                return $date->format('d-m-Y');
            })->editColumn('date_end',function($entity){
                $date = Carbon::parse($entity->date_end);
                return $date->format('d-m-Y');
            })->rawColumns(['actions', 'image'])
            ->setRowAttr([
                'data-id' => function($entity) {
                    return $entity->id;
                }
            ])
            ->make(true);
    }
    
    public function create()
    {   
        $entity = new Entity();

        $companies = CompanyProcurement::all();
        
        return view('truck.invoices_procurement.create', [
            'entity' => $entity,
            'companies' => $companies
        ]);
    }
    
    public function store()
    {   
        $request = $this->request;
        
        $data = $request->validate([
            'id_invoice' => ['required', 'string', 'max:190'],
            'company' => ['required', 'integer', 'exists:truck_companies,id'],
            'date_start' => ['required', 'string', 'date_format:d-m-Y'],
            'date_end' => ['required', 'string', 'date_format:d-m-Y', 'after_or_equal:date_start'],
            'price' => ['required', 'string', 'max:20'],
            'currency' => ['required', 'string', 'max:20'],
            'text' => ['required', 'string', 'max:900']

        ]);

        $data['date_start'] = date('Y-m-d',strtotime(request()->date_start));
        $data['date_end'] = date('Y-m-d',strtotime(request()->date_end));

        $entity = new Entity();
        
        $entity->fill($data);
        $entity->save();
        
        
        if ($request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Faktura je uspešno sačuvana!'));
        }
        
        return redirect()->route('truck.invoices_procurement')->withSystemSuccess(__('Faktura je uspešno sačuvana!'));
    }
    
    public function edit(Entity $entity)
    {
        $companies = CompanyProcurement::all();

        return view('truck.invoices_procurement.edit', [
            'entity' => $entity,
            'companies' => $companies
        ]);
    }
    
    public function update(Entity $entity)
    {
        $request = $this->request;
        
        $data = $request->validate([
            'id_invoice' => ['required', 'string', 'max:190'],
            'company' => ['required', 'integer', 'exists:truck_companies,id'],
            'date_start' => ['required', 'string', 'date_format:d-m-Y'],
            'date_end' => ['required', 'string', 'date_format:d-m-Y', 'after_or_equal:date_start'],
            'price' => ['required', 'string', 'max:20'],
            'currency' => ['required', 'string', 'max:20'],
            'text' => ['required', 'string', 'max:900']
        ]);

        $data['date_start'] = date('Y-m-d',strtotime(request()->date_start));
        $data['date_end'] = date('Y-m-d',strtotime(request()->date_end));
        
        $entity->fill($data);
        $entity->save();
        
        if ($request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Faktura je uspešno izmenjena!'));
        }
        
        return redirect()->route('truck.invoices_procurement')->withSystemSuccess(__('Faktura je uspešno izmenjena!'));
    }
    
    public function delete(Entity $entity)
    {
        $entity->delete();
        
        if ($this->request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Faktura je uspešno obrisana!'));
        }
        
        return redirect()->route('truck.invoices_procurement.index')->withSystemSuccess(__('Faktura je uspešno obrisana!'));
    }

    public function paid(Entity $entity)
    {
        $entity->status = 1;
        $entity->date_done =  Carbon::now();
        $entity->update();
        
        if ($this->request->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Potvrda placanja je uspešno sacuvana!'));
        }
        
        return redirect()->route('truck.invoices_procurement.index')->withSystemSuccess(__('Potvrda placanja je uspesno sacuvana!'));
    }

    public function getSummary()
    {
        $pendingEur = Entity::where('status', 0)->where('currency', 'EUR')->sum('price'); 
        $pendingKm = Entity::where('status', 0)->where('currency', 'KM')->sum('price'); 
        $paidEur = Entity::where('status', 1)->where('currency', 'EUR')->sum('price'); 
        $paidKm = Entity::where('status', 1)->where('currency', 'KM')->sum('price');

        $response = [
            'pending' => [
                'eur' => $pendingEur,
                'km' => $pendingKm
            ],
            'paid' => [
                'eur' => $paidEur,
                'km' => $paidKm
            ]
        ];

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

    public function A4View($id)
    {
        $invoice = Entity::findOrFail($id);
        $company = CompanyProcurement::findOrFail($invoice->company);

        return view('truck.invoices_procurement.A4View', compact('invoice', 'company'));
    }


}
