<?php

namespace App\Http\Controllers;

//change the request class if needed

use Akaunting\Setting\Drivers\Json;
use Illuminate\Http\Request as Request;
use App\Models\Truck\InvoicePayment as Entity;
use App\Models\Truck\Invoice;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTables;
use App\Http\Resources\JsonResource;
use App\Models\Truck\Company;
use Illuminate\Http\File;

class TruckFinanceController extends Controller
{

    protected $namespace = 'truck.finance.';

    public function index()
    {
        $companies = Company::all();

        return view($this->namespace . 'index', [
            'entity' => new Entity(),
            'namespace' => $this->namespace,
            'defaultHexColor' => '#305AA2',
            'companies' => $companies
        ]);
    }

    public function store()
    {

        $entity = new Entity;

        $data = request()->validate(self::rules($entity));

        $entity->fill($data);

        $entity->save();

        $this->handleUploadedImage($entity);

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Autor je uspešno sačuvan!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Autor je uspešno sačuvan!'));
    }

    public function edit(Entity $entity)
    {
        return view($this->namespace . 'edit', [
            'entity' => $entity,
            'namespace' => $this->namespace,
            'defaultHexColor' => '#305AA2'
        ]);
    }

    public function update(Entity $entity)
    {
        
        $data = request()->validate(self::rules($entity));

        if(request()->input('delete_logo')){
            $entity->deleteLogo();
        }

        $entity->fill($data);

        $entity->save();

        $this->handleUploadedImage($entity);

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Autor je uspešno editovan!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Autor je uspešno editovan!'));;
    }

    public function delete(Entity $entity)
    {

        $entity->delete();

        if (request()->wantsJson()) {
            return JsonResource::make()->withSuccess(__('Autor je uspešno obrisan!'));
        }

        return redirect()->route($this->namespace . 'index')->withSystemSuccess(__('Autor je uspešno obrisan!'));
    }



    public function datatable()
    {
        $entities = Entity::query()->orderBy('created_at', 'desc');

        $entities->get();

        $datatable = datatables($entities)
        ->addColumn('actions', function ($entity) {
            return view('truck.finance.partials.table.actions', [
                'entity' => $entity,
            ]);
        })->editColumn('company', function ($entity) {
            $company = Company::where('id', $entity->company)->first();
            return optional($company)->name ?: 'N/A';

        })->editColumn('created_at', function ($entity) {
            $date = new \DateTime($entity->created_at);
            $formattedDate = $date->format('d-m-Y');
            return $formattedDate;
        })->editColumn('price', function ($entity) {
            return $entity->price . ' ' . $entity->currency;
        });

        $datatable->rawColumns(['actions']);

        return $datatable->make(true);
    }

    public function getInvoices(Request $request)
    {
        $companyId = $request->id;

        $invoices = Invoice::where('company', $companyId)
                    ->whereNull('deleted_at')
                    ->where('status', 0)
                    ->get();

        return response()->json(['invoices' => $invoices]);
    }

    public function addNewPayment(Request $request){

        $request->validate([
            'company' => [
                'required',
                'integer',
                Rule::exists('truck_companies', 'id')
            ],
            'reference' => 'nullable|string|max:255',
            'currency' => 'required|in:EUR,KM',
            'date_start' => 'required|date',
            'price' => 'required|numeric|min:0.01'
        ]);
        
        $companyId = $request->input('company');
        $reference = $request->input('reference');
        $currency = $request->input('currency');
        $dateStart = $request->input('date_start');
        $price = (float) $request->input('price');

        // Pronađi neplaćene fakture za datu kompaniju
        $invoices = Invoice::where('company', $companyId)
                    ->whereNull('deleted_at')
                    ->where('status', 0)
                    ->orderBy('created_at', 'asc') // Redosled da bi prvo obrađivali starije fakture
                    ->get();


        foreach ($invoices as $invoice) {
            if ($price <= 0) {
                break; // Ako nema više novca za plaćanje, izađi iz petlje
            }
    
            $invoiceAmount = (float) $invoice->debt;

            if ($price >= $invoiceAmount) {
                // Ako imamo dovoljno novca za potpuno plaćanje fakture
                $invoice->status = 1; // Faktura je plaćena
                $invoice->price_part = 0;
                $invoice->debt = $invoice->price;
                $invoice->save();
                $price -= $invoiceAmount; // Oduzmi iznos fakture od ukupnog novca
            } else {
                // Ako imamo samo delimično novca za plaćanje fakture
                $invoice->price_part = $invoice->price_part + $price; // Upisujemo delimično plaćen iznos
                $invoice->debt = $invoice->debt + ($invoice->price - $invoice->price_part);
                $invoice->save();
                $price = 0; // Sve preostale vrednosti su isplaćene
            }
        }
    
        // if ($price > 0) {
        //     // Pronađi kompaniju i dodaj preostali novac u 'extra_money'
        //     $company = Company::find($companyId);
        
        //     if ($company) {
        //         // Pretpostavljamo da `extra_money` polje postoji u modelu Company
        //         $company->extra_money = $price; // Dodaj preostali novac
        //         $company->save();
        //     }
        // }
        $date = \DateTime::createFromFormat('d-m-Y', $dateStart);
        $formattedDate = $date->format('Y-m-d');
        // Kreiraj novi zapis u tabeli invoice_payment
        Entity::create([
            'company' => $companyId,
            'price' => $request->input('price'),
            'currency' => $currency,
            'date_start' => $formattedDate,
            'reference' => $reference,
        ]);


        
        return redirect()->route('truck_finance_invoice_payments')->withSystemSuccess(__('Uplata je uspešno sačuvana!'));
    }

    protected function rules($entity)
    {
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'biography' => ['nullable', 'string',  'max:500'],
            'twitter' => ['nullable', 'string',  'max:150'],
            'photo' => ['nullable', 'file', 'image'],
            'menu_color' => ['nullable', 'string', 'min:7', 'max:7'],
            'text_color' => ['nullable', 'string', 'min:7', 'max:7'],
            'four_big_news' => ['nullable', 'numeric','in:0,1'],
        ];

        return $rules;
    }
}
