<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\FinancialTransaction;
use App\Models\CustomerWalletTransaction;
use App\Models\FinancialTreasury;

class FinancialTransactionController extends Controller
{
    public function index(Request $request)
    {
        $treasuries = FinancialTreasury::all();

        // Treasury Transactions
        $treasuryQuery = FinancialTransaction::with(['treasury', 'category', 'user'])
            ->latest();

        if ($request->filled('date_from')) {
            $treasuryQuery->whereDate('date', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $treasuryQuery->whereDate('date', '<=', $request->date_to);
        }
        if ($request->filled('treasury_id')) {
            $treasuryQuery->where('treasury_id', $request->treasury_id);
        }

        $treasuryTransactions = $treasuryQuery->paginate(20, ['*'], 'treasury_page')->withQueryString();

        // Wallet Transactions
        $walletQuery = CustomerWalletTransaction::with(['customer', 'user'])
            ->latest();

        if ($request->filled('date_from')) {
            $walletQuery->whereDate('date', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $walletQuery->whereDate('date', '<=', $request->date_to);
        }

        $walletTransactions = $walletQuery->paginate(20, ['*'], 'wallet_page')->withQueryString();

        return view('accounting.transactions.index', compact('treasuryTransactions', 'walletTransactions', 'treasuries'));
    }
    public function destroy(FinancialTransaction $transaction)
    {
        try {
            \Illuminate\Support\Facades\DB::beginTransaction();

            // 1. Revert Treasury Balance
            $treasury = $transaction->treasury;
            if ($treasury) {
                if ($transaction->type == 'in') {
                    $treasury->decrement('balance', $transaction->amount);
                } elseif ($transaction->type == 'out') {
                    $treasury->increment('balance', $transaction->amount);
                }
            }

            // 2. Handle Linked Models
            if ($transaction->model_type && $transaction->model_id) {
                $model = $transaction->model;

                if ($model) {
                    // Invoice Payment Reversal
                    if ($transaction->model_type == 'App\Models\Invoice' && $transaction->type == 'in') {
                        $model->decrement('paid_amount', $transaction->amount);

                        $newStatus = 'unpaid';
                        if ($model->paid_amount >= $model->total) {
                            $newStatus = 'paid';
                        } elseif ($model->paid_amount > 0) {
                            $newStatus = 'partially_paid';
                        }
                        $model->update(['status' => $newStatus]);
                    }
                    // Bill Payment Reversal
                    elseif ($transaction->model_type == 'App\Models\Bill' && $transaction->type == 'out') {
                        $model->decrement('paid_amount', $transaction->amount);

                        $newStatus = 'unpaid';
                        if ($model->paid_amount >= $model->total) {
                            $newStatus = 'paid';
                        } elseif ($model->paid_amount > 0) {
                            $newStatus = 'partial'; // Verify enum
                        }
                        $model->update(['status' => $newStatus]);
                    }
                    // Wallet Transaction Deletion
                    elseif ($transaction->model_type == 'App\Models\CustomerWalletTransaction') {
                        // Deleting the wallet transaction triggers observers to revert customer balance
                        $model->delete();
                    }
                }
            }

            $transaction->delete();

            \Illuminate\Support\Facades\DB::commit();

            return back()->with('success', 'Transaction deleted successfully.');

        } catch (\Exception $e) {
            \Illuminate\Support\Facades\DB::rollBack();
            return back()->with('error', 'Error deleting transaction: ' . $e->getMessage());
        }
    }
}
