<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\PaymentTransactionDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\PaymentTransactions\StoreUpdatePaymentTransactionsRequest;
use App\Models\Customer;
use App\Models\PaymentTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\View;
use Illuminate\Validation\Rule;


class PaymentTransactionsController extends Controller
{
    public function index(PaymentTransactionDataTable $dataTable)
    {
        abort_if(Gate::denies('transaction_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');
        return $dataTable->render('admin.payment_transactions.index');
    }

    public function create()
    {
        abort_if(Gate::denies('transaction_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');
        $customers = Customer::orderBy('name')->get();
        // $currentDate = Carbon::now()->format('Y-m-d');
        $invoice_number = getNewInvoiceNumber('','new_cash_receipt',Carbon::now()->format('Y-m-d'));
        return view('admin.payment_transactions.create', compact('customers','invoice_number'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreUpdatePaymentTransactionsRequest $request)
    {
        $cashReceiptAmountsData = [];
        foreach ($request->payment_way as $i => $way) {
            $cashReceiptAmountsData[] = [
                'payment_way' => $way,
                'amount'      => $request->amount[$i] ?? 0,
            ];
            
        }

        $totalAmount = collect($cashReceiptAmountsData)->sum('amount');
        $customer = Customer::find($request->customer_id);
        $voucherNumber = null;
        if ($customer && $customer->customer_type !== 'cash') {
            $voucherNumber = $request->voucher_number ?: getNewInvoiceNumber('', 'new_cash_receipt', $request->entry_date);
        }

        $paymentTransaction = PaymentTransaction::create([
            'customer_id'    => $request->customer_id,
            'voucher_number' => $voucherNumber,
            'payment_type'   => 'credit',
            'payment_way'    => 'by_cash',
            'amount'         => $totalAmount,
            'entry_date'     => $request->entry_date,
            'remark'         => $request->remark ?? 'Cash Receipt',
        ]);
        
        foreach ($cashReceiptAmountsData as $cashReceiptAmount) {
            $paymentTransaction->cashReceiptAmounts()->create($cashReceiptAmount);
            if (($cashReceiptAmount['payment_way'] ?? null) === 'by_cash') {
                storeCashBalanceRecord($paymentTransaction, 'credit', $request->entry_date);
            }
        }

        addToLog($request, 'Cash receipt', 'Create', $paymentTransaction);

            $invoiceMessage = $customer && $customer->customer_type === 'cash'
            ? 'Cash Receipt'
            : 'Cash Receipt No. #' . $paymentTransaction->voucher_number;

        return response()->json([
            'success'       => true,
            'message'       => trans('messages.crud.add_record'),
            'alert-type'    => trans('quickadmin.alert-type.success'),
            'invoiceNumber' => $invoiceMessage,
            'redirectUrl'   => route('transactions.index'),
        ], 200);
    }


    /**
     * Display the specified resource.
     */
    public function show(Request $request,PaymentTransaction $transaction)
    {
        abort_if(Gate::denies('transaction_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');
        $htmlView = view('admin.payment_transactions.show',compact('transaction'))->render();
        return response()->json(['success' => true, 'htmlView' => $htmlView]);        
    }    
    

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(PaymentTransaction $transaction)
    {        
        abort_if(Gate::denies('transaction_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');        
        $customers = Customer::orderBy('name')->get();
        $customer = Customer::where('id', $transaction->customer_id)->first();  
        $debit_balance = $customer->debit_balance ?? 0;
        $credit_balance = $customer->credit_balance ?? 0;
        $remainingbalance = round($debit_balance - $credit_balance, 2);
        $transaction->load('cashReceiptAmounts');
        $invoice_number = getNewInvoiceNumber('', 'new_cash_receipt', now()->format('Y-m-d'));
        
        return view('admin.payment_transactions.edit', compact('customers', 'transaction','remainingbalance','invoice_number'));
    }

    /**
     * Update the specified resource in storage.
     */
    
    public function update(Request $request, PaymentTransaction $transaction)
    {
        abort_if(Gate::denies('transaction_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');
        $customerId = $request->input('customer_id');
        $customer = \App\Models\Customer::find($customerId);
        $voucherRules = [];

        if ($customer && $customer->customer_type === 'cash') {
            $voucherRules = [
                'nullable',
                Rule::unique('payment_transactions', 'voucher_number')
                    ->ignore($transaction->id)
                    ->whereNull('deleted_at'),
            ];
        } else {
            $voucherRules = [
                'required',
                Rule::unique('payment_transactions', 'voucher_number')
                    ->ignore($transaction->id)
                    ->whereNull('deleted_at'),
            ];
        }

        $validated = $request->validate([
            'customer_id'    => 'required|exists:customers,id',
            'voucher_number' => $voucherRules,
            'payment_way'   => 'required|array',
            'payment_way.*' => 'required|in:by_cash,by_phonepay,by_check,by_account',
            'amount'        => 'required|array',
            'amount.*'      => 'required|regex:/^\d+(\.\d{1,4})?$/',
            'entry_date'     => 'required|date',
            'remark'            => 'nullable|string|max:255',
        ],
            [], 
        [
            'voucher_number' => 'Estimate number', 
        ]
        );


        $paymentWays = $request->input('payment_way', []); 
        $amounts     = $request->input('amount', []);

        $cashReceiptAmountsData = [];
        foreach ($paymentWays as $i => $way) {
            $cashReceiptAmountsData[] = [
                'payment_way' => $way,
                'amount'      => $amounts[$i] ?? 0,
            ];
        }

        $totalAmount = collect($cashReceiptAmountsData)->sum('amount');
        $oldvalue    = $transaction->getOriginal();
        $voucherNumber = $customer && $customer->customer_type === 'cash' ? null : $request->voucher_number;
        $transaction->update([
            'customer_id'    => $request->customer_id,
            'voucher_number' => $voucherNumber,
            'payment_type'   => 'credit',
            'payment_way'   => 'by_cash',
            'amount'         => $totalAmount,
            'entry_date'     => $request->entry_date,
            'remark'         => $request->remark ?? 'Cash Receipt',
        ]);

        $transaction->cashReceiptAmounts()->delete();

        foreach ($cashReceiptAmountsData as $cashReceiptAmounts) {
            $transaction->cashReceiptAmounts()->create($cashReceiptAmounts);
        }

        $newValue = $transaction->refresh();
        addToLog($request, 'Cash receipt', 'Edit', $newValue, $oldvalue);

        $invoiceMessage = $customer && $customer->customer_type === 'cash'
            ? 'Cash Receipt'
            : 'Cash Receipt No. #' . $transaction->voucher_number;

        return response()->json([
            'success'       => true,
            'message'       => trans('messages.crud.update_record'),
            'alert-type'    => trans('quickadmin.alert-type.success'),
            'invoiceNumber' => $invoiceMessage,
            'redirectUrl'   => route('transactions.index'),
        ], 200);
    }
    

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(PaymentTransaction $transaction)
    {
        abort_if(Gate::denies('transaction_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');      
        $transaction->delete();
        return response()->json(['success' => true,
         'message' => trans('messages.crud.delete_record'),
         'alert-type'=> trans('quickadmin.alert-type.success'),
         'title' => trans('quickadmin.transaction.title_singular')
        ], 200);
    }
    
}
