<?php

namespace App\Http\Controllers;

use App\Models\Budget;
use App\Models\CreditLine;
use App\Models\Currency;
use App\Models\StatementOfAccount;
use App\Models\TransactionDetail;
use App\Models\Transactions;
use App\Models\VoucherType;
use App\Models\warehouse;
use Illuminate\Http\Request;
use Inertia\Inertia;

class StatementOfAccountController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $query = StatementOfAccount::where('status', 1)
            ->with('person')
            ->with('transaction_details')
            ->with('voucher')
            ->where('type_transaction', request()->input('type_transaction'))
            ->latest('id');

        $statementOfAccounts = $query->paginate(10)->withQueryString();
       return Inertia::render('StatementOfAccounts/Index', [
            'statement_of_accounts' => $statementOfAccounts,
            'type_transaction' => request()->input('type_transaction')
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $currencies = Currency::all();
        $voucherTypes = VoucherType::all();
        $warehouse = warehouse::with('establishment')->first();

        return Inertia::render('StatementOfAccounts/CreateEdit', [
            'currencies' => $currencies,
            'warehouse' => $warehouse,
            'voucherTypes' => $voucherTypes,
            'type_transaction' => request()->input('type_transaction')
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        \DB::transaction(function () use ($request) {
            $person_id = $request->input('person_id');
            $currency_id = $request->input('currency_id');
            $amountToPay = $request->input('amount_to_pay');
            $statementOfAccounts = $request->input('selected_documents');
            $observations = $request->input('observations');
            $amountToPayTotal = $amountToPay;

            $voucherNumbers = collect($statementOfAccounts)->map(function ($statementOfAccount) {
                return $statementOfAccount['voucherNumber'];
            })->implode(', ');

            $descriptionAutomaticTransaction = 'Documento(s) Afectado(s) ' . $voucherNumbers .
                ' - Monto Total Ingresado: ' . $amountToPayTotal .
                ' - Monto Pagado: ' . $amountToPayTotal .
                ' Los montos fueron redistribuidos en los Documentos Afectados';

            $transaction = new Transactions();
            $transaction->person_id = $person_id;
            $transaction->currency_id = $currency_id;
            $transaction->type_transaction = $request->input('type_transaction');
            $transaction->total = $amountToPayTotal;
            $transaction->issue_date = now()->toDateString();
            $transaction->description = $observations;
            $transaction->descriptionAutomatic = $descriptionAutomaticTransaction;
            $transaction->status = 1;
            $transaction->save();
            $transactionId = $transaction->id;

            foreach ($statementOfAccounts as $statementOfAccount) {
                $id = $statementOfAccount['id'];
                $saldoCuenta = $statementOfAccount['saldo'];
                if ($saldoCuenta <= $amountToPay) {
                    $totalbytransaction = $saldoCuenta;
                    $saldoPago = $amountToPay - $saldoCuenta;

                } else {
                    $totalbytransaction = $amountToPay;
                    $saldoPago = $saldoCuenta - $amountToPay;
                }

                $descriptionAutomatic = 'Documento(s) Afectado(s) ' . $voucherNumbers .
                    ' - Monto Total Ingresado: ' . $amountToPayTotal .
                    ' - Monto Pagado: ' . $totalbytransaction .
                    ' Los montos restantes fueron aplicados a otros documentos afectados';
                $transaction = new TransactionDetail();
                $transaction->statement_of_account_id = $id;
                $transaction->transaction_id = $transactionId;
                $transaction->type_transaction = $request->input('type_transaction');
                $transaction->total = $totalbytransaction;
                $transaction->issue_date = now()->toDateString();
                $transaction->description = $observations;
                $transaction->descriptionAutomatic = $descriptionAutomatic;
                $transaction->status = 1;
                $transaction->save();

                $typeTransaction = $request->input('type_transaction') === 'sales' ?  'output' :  'entry';
                if($typeTransaction === 'output' ){
                    $creditLine = CreditLine::where('person_id', $person_id)->first();
                    if ($creditLine) {
                        $creditLine->used -= $totalbytransaction;
                        $creditLine->residue =  $creditLine->total - $creditLine->used;
                        $creditLine->save();
                    }
                }

                if ($saldoCuenta <= $amountToPay) {
                    StatementOfAccount::where('id', $id)->update(['payment_status' => 1]);
                }
                if ($saldoPago == 0) {
                    break;
                }
                $amountToPay = $saldoPago;
            }
        });
/*        return redirect()->route($request->input('type_transaction') === 'sales'
            ? 'CollectCashFlow.statement_of_accounts.create'
            : 'PayCashFlow.statement_of_accounts.create');*/
    }

    /**
     * Display the specified resource.
     */
    public function showByPerson(Request $request, $person_id)
    {
        $query = StatementOfAccount::where('status', 1)
            ->where('payment_status', 0)
            ->where('person_id', $person_id)
            ->whereHas('voucher', function ($query) use ($request) {
                $query->where('currency_id', $request->input('currency_id'));
            })
            ->whereHas('voucher', function ($query) use ($request) {
                $query->where('voucher_type_id', $request->input('voucher_type_id_filter'));
            })
            ->with('person', 'transaction_details', 'voucher')
            ->where('type_transaction', $request->input('type_transaction'))
            ->latest('id');

        $statement_of_accounts = $query->paginate(10)->withQueryString();
        if (!$statement_of_accounts) {
            return response()->json(['message' => 'Statement of Account not found'], 404);
        }
        return response()->json($statement_of_accounts);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(StatementOfAccount $statementOfAccount)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, StatementOfAccount $statementOfAccount)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(StatementOfAccount $statementOfAccount)
    {
        //
    }
}
