<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TransactionApiController extends Controller
{
    /**
     * Get all transactions with pagination and filtering
     */
    public function index(Request $request)
    {
        try {
            $query = Transaction::with('user');

            // Search functionality
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->where('reference', 'LIKE', "%{$search}%")
                      ->orWhere('description', 'LIKE', "%{$search}%")
                      ->orWhereHas('user', function($userQuery) use ($search) {
                          $userQuery->where('name', 'LIKE', "%{$search}%")
                                   ->orWhere('email', 'LIKE', "%{$search}%");
                      });
                });
            }

            // Type filter
            if ($request->has('type')) {
                $query->where('type', $request->type);
            }

            // Wallet filter
            if ($request->has('wallet')) {
                $query->where('wallet', $request->wallet);
            }

            // Status filter
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // Amount range filter
            if ($request->has('amount_min')) {
                $query->where('amount', '>=', $request->amount_min);
            }
            if ($request->has('amount_max')) {
                $query->where('amount', '<=', $request->amount_max);
            }

            // Date filter
            if ($request->has('date_from')) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }
            if ($request->has('date_to')) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }

            $perPage = $request->per_page ?? 15;
            $transactions = $query->orderBy('created_at', 'desc')->paginate($perPage);

            // Add summary statistics
            $summary = [
                'total_amount' => $query->sum('amount'),
                'credit_amount' => Transaction::where('type', 'credit')->sum('amount'),
                'debit_amount' => Transaction::where('type', 'debit')->sum('amount'),
                'total_count' => $query->count(),
            ];

            return response()->json([
                'status' => 'success',
                'data' => $transactions,
                'summary' => $summary
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch transactions',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get specific transaction details
     */
    public function show($id)
    {
        try {
            $transaction = Transaction::with('user')->findOrFail($id);

            return response()->json([
                'status' => 'success',
                'data' => $transaction
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Transaction not found',
                'error' => $e->getMessage()
            ], 404);
        }
    }

    /**
     * Create manual transaction
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required|exists:users,id',
                'type' => 'required|in:credit,debit',
                'amount' => 'required|numeric|min:0.01',
                'wallet' => 'required|in:deposit_wallet,interest_wallet,bonus_wallet',
                'description' => 'required|string|max:500',
                'reference' => 'nullable|string|max:100',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $user = User::findOrFail($request->user_id);
            $wallet = $request->wallet;
            $type = $request->type;
            $amount = $request->amount;

            // Check if debit and sufficient balance
            if ($type === 'debit' && $user->$wallet < $amount) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Insufficient balance in selected wallet'
                ], 400);
            }

            // Update wallet balance
            if ($type === 'credit') {
                $user->increment($wallet, $amount);
            } else {
                $user->decrement($wallet, $amount);
            }

            // Create transaction record
            $transaction = Transaction::create([
                'user_id' => $user->id,
                'type' => $type,
                'amount' => $amount,
                'description' => $request->description,
                'wallet' => $wallet,
                'balance_after' => $user->fresh()->$wallet,
                'reference' => $request->reference ?? 'MAN-' . strtoupper(uniqid()),
                'status' => 'completed',
                'created_by' => auth()->id()
            ]);

            return response()->json([
                'status' => 'success',
                'message' => 'Manual transaction created successfully',
                'data' => $transaction
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to create transaction',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update transaction
     */
    public function update(Request $request, $id)
    {
        try {
            $transaction = Transaction::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'description' => 'sometimes|string|max:500',
                'reference' => 'sometimes|string|max:100',
                'status' => 'sometimes|in:pending,completed,failed',
                'admin_note' => 'nullable|string|max:1000'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $transaction->update($validator->validated());

            return response()->json([
                'status' => 'success',
                'message' => 'Transaction updated successfully',
                'data' => $transaction
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to update transaction',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete transaction
     */
    public function destroy($id)
    {
        try {
            $transaction = Transaction::findOrFail($id);
            
            if ($transaction->status === 'completed') {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot delete completed transactions'
                ], 400);
            }

            $transaction->delete();

            return response()->json([
                'status' => 'success',
                'message' => 'Transaction deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to delete transaction',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get transaction statistics
     */
    public function statistics(Request $request)
    {
        try {
            $period = $request->period ?? 'all';
            
            $query = Transaction::query();
            
            switch ($period) {
                case 'today':
                    $query->whereDate('created_at', today());
                    break;
                case 'week':
                    $query->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]);
                    break;
                case 'month':
                    $query->whereMonth('created_at', now()->month);
                    break;
                case 'year':
                    $query->whereYear('created_at', now()->year);
                    break;
            }

            $stats = [
                'total_transactions' => $query->count(),
                'total_amount' => $query->sum('amount'),
                'credit_transactions' => $query->where('type', 'credit')->count(),
                'credit_amount' => $query->where('type', 'credit')->sum('amount'),
                'debit_transactions' => $query->where('type', 'debit')->count(),
                'debit_amount' => $query->where('type', 'debit')->sum('amount'),
                'completed_transactions' => $query->where('status', 'completed')->count(),
                'pending_transactions' => $query->where('status', 'pending')->count(),
                'failed_transactions' => $query->where('status', 'failed')->count(),
                'average_amount' => $query->avg('amount'),
                'wallet_breakdown' => Transaction::selectRaw('wallet, COUNT(*) as count, SUM(amount) as total_amount')
                                                 ->groupBy('wallet')
                                                 ->get(),
            ];

            return response()->json([
                'status' => 'success',
                'data' => $stats,
                'period' => $period
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch transaction statistics',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Export transactions
     */
    public function export(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'format' => 'required|in:csv,excel,pdf',
                'date_from' => 'nullable|date',
                'date_to' => 'nullable|date',
                'type' => 'nullable|in:credit,debit',
                'wallet' => 'nullable|in:deposit_wallet,interest_wallet,bonus_wallet',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $query = Transaction::with('user');

            // Apply filters
            if ($request->date_from) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }
            if ($request->date_to) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }
            if ($request->type) {
                $query->where('type', $request->type);
            }
            if ($request->wallet) {
                $query->where('wallet', $request->wallet);
            }

            $transactions = $query->orderBy('created_at', 'desc')->get();

            // Format data for export
            $exportData = $transactions->map(function($transaction) {
                return [
                    'ID' => $transaction->id,
                    'User' => $transaction->user->name ?? 'N/A',
                    'Email' => $transaction->user->email ?? 'N/A',
                    'Type' => ucfirst($transaction->type),
                    'Amount' => number_format($transaction->amount, 2),
                    'Wallet' => ucfirst(str_replace('_', ' ', $transaction->wallet)),
                    'Description' => $transaction->description,
                    'Reference' => $transaction->reference,
                    'Status' => ucfirst($transaction->status),
                    'Balance After' => number_format($transaction->balance_after, 2),
                    'Date' => $transaction->created_at->format('Y-m-d H:i:s'),
                ];
            });

            return response()->json([
                'status' => 'success',
                'message' => 'Export data prepared successfully',
                'data' => $exportData,
                'total_records' => $exportData->count()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to export transactions',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}