<?php

namespace App\Http\Controllers;
use App\Loan;
use App\Customer;
use App\Installment;
use App\LoanPayment;
use App\BankAccount;
use App\LoanSaving;
use App\DpsAccount;
use App\DpsInstallment;
use App\DpsWithdrawal;
use App\DpsPayment;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;


class PaymentController extends Controller
{
    public function index(Request $request)
    {
        $perPage = 20; // change if needed
        $page = $request->get('page', 1);
    
        // -------------------------------
        // Loan Payments
        // -------------------------------
        $loanPayments = LoanPayment::with(['loan.customer', 'installment', 'bankAccount'])
            ->when($request->customer_id, function ($q) use ($request) {
                $q->whereHas('loan', function ($q) use ($request) {
                    $q->where('customer_id', $request->customer_id);
                });
            })
            ->when($request->from_date, fn($q) => $q->whereDate('payment_date', '>=', $request->from_date))
            ->when($request->to_date, fn($q) => $q->whereDate('payment_date', '<=', $request->to_date))
            ->get()
            ->map(function ($p) {
                return [
                    'type'     => 'Loan Payment',
                    'type_key' => 'loan',
                    'id'       => $p->id,
                    'date'     => $p->payment_date,
                    'customer' => $p->loan->customer->name ?? '-',
                    'details'  => 'Loan Inst #' . ($p->installment->installment_no ?? '-'),
                    'amount'   => $p->amount,
                    'bank'     => $p->bankAccount->name ?? '-',
                ];
            });
    
        // -------------------------------
        // DPS Payments
        // -------------------------------
        $dpsPayments = DpsPayment::with(['installment.dpsAccount.customer', 'bankAccount'])
            ->when($request->customer_id, function ($q) use ($request) {
                $q->whereHas('installment.dpsAccount', function ($q) use ($request) {
                    $q->where('customer_id', $request->customer_id);
                });
            })
            ->when($request->from_date, fn($q) => $q->whereDate('paid_at', '>=', $request->from_date))
            ->when($request->to_date, fn($q) => $q->whereDate('paid_at', '<=', $request->to_date))
            ->get()
            ->map(function ($p) {
                return [
                    'type'     => 'DPS Payment',
                    'type_key' => 'dps',
                    'id'       => $p->id,
                    'date'     => $p->paid_at,
                    'customer' => $p->installment->dpsAccount->customer->name ?? '-',
                    'details'  => 'DPS Installment',
                    'amount'   => $p->amount,
                    'bank'     => $p->bankAccount->name ?? '-',
                ];
            });
    
        // -------------------------------
        // Merge & Sort
        // -------------------------------
        $allPayments = $loanPayments
            ->merge($dpsPayments)
            ->sortByDesc('date')
            ->values();
    
        // -------------------------------
        // Manual Pagination
        // -------------------------------
        $payments = new LengthAwarePaginator(
            $allPayments->forPage($page, $perPage),
            $allPayments->count(),
            $perPage,
            $page,
            [
                'path'  => request()->url(),
                'query' => request()->query(), // keeps filters
            ]
        );
    
        $customers = Customer::orderBy('name')->get();
    
        return view('pages.payments.index', compact('payments', 'customers'));
    }



    // 🔴 Delete Loan Payment
   public function deleteLoan($id)
    {
        DB::transaction(function () use ($id) {

            $payment = LoanPayment::findOrFail($id);
            $installment = Installment::findOrFail($payment->installment_id);
            $bank = BankAccount::findOrFail($payment->bank_account_id);

            // Delete all savings linked to this payment
            $savingsList = LoanSaving::where('loan_payment_id', $payment->id)->get();
            foreach ($savingsList as $saving) {
                $bank->current_balance -= $saving->amount;
                $saving->delete();
            }

            // Reverse the loan payment
            $bank->current_balance -= $payment->amount;

            $installment->paid_amount -= $payment->amount;
            if ($installment->paid_amount <= 0) {
                $installment->paid_amount = 0;
                $installment->status = 'pending';
                $installment->paid_date = null;
            }

            $installment->save();
            $bank->save();

            // Delete the payment
            $payment->delete();
        });

        return back()->with('success', 'Loan payment and associated savings deleted successfully.');
    }



    // 🔴 Delete DPS Payment
    public function deleteDps($id)
    {
        DB::transaction(function () use ($id) {

            $payment = DpsPayment::findOrFail($id);
            $installment = DpsInstallment::findOrFail($payment->dps_installment_id);
            $bank = BankAccount::findOrFail($payment->bank_account_id);

            $bank->current_balance -= $payment->amount;
            $bank->save();

            $installment->remaining_amount += $payment->amount;
            $installment->is_paid = 0;
            $installment->paid_at = null;
            $installment->save();

            $payment->delete();
        });

        return back()->with('success', 'DPS payment deleted.');
    }
    
    public function bulkDelete(Request $request)
    {
        $payments = $request->input('payments', []);

        if (empty($payments)) {
            return back()->with('error', 'No payments selected');
        }

        DB::transaction(function () use ($payments) {
            foreach ($payments as $item) {
                [$type, $id] = explode('|', $item);

                if ($type === 'loan') {
                    $this->deleteLoanPaymentById($id);
                } elseif ($type === 'dps') {
                    $this->deleteDpsPaymentById($id);
                }
            }
        });

        return back()->with('success', 'Selected payments deleted successfully.');
    }

    // Helper to delete a loan payment correctly
    protected function deleteLoanPaymentById($id)
    {
        $payment = LoanPayment::findOrFail($id);
        $installment = Installment::findOrFail($payment->installment_id);
        $bank = BankAccount::findOrFail($payment->bank_account_id);

        // Delete linked savings
        $savingsList = LoanSaving::where('loan_payment_id', $payment->id)->get();
        foreach ($savingsList as $saving) {
            $bank->current_balance -= $saving->amount;
            $saving->delete();
        }

        // Reverse the payment
        $bank->current_balance -= $payment->amount;
        $installment->paid_amount -= $payment->amount;

        if ($installment->paid_amount <= 0) {
            $installment->paid_amount = 0;
            $installment->status = 'pending';
            $installment->paid_date = null;
        }

        $installment->save();
        $bank->save();
        $payment->delete();
    }

    // Helper to delete a DPS payment correctly
    protected function deleteDpsPaymentById($id)
    {
        $payment = DpsPayment::findOrFail($id);
        $installment = DpsInstallment::findOrFail($payment->dps_installment_id);
        $bank = BankAccount::findOrFail($payment->bank_account_id);

        $bank->current_balance -= $payment->amount;
        $bank->save();

        $installment->remaining_amount += $payment->amount;
        $installment->is_paid = 0;
        $installment->paid_at = null;
        $installment->save();

        $payment->delete();
    }


}
