<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CoinTransaction;
use App\Models\ShowPurchase;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class TransactionController extends Controller
{
    /**
     * Display a listing of all transactions.
     */
    public function index(Request $request): Response
    {
        $type = $request->get('type', 'all');
        $status = $request->get('status');
        $search = $request->get('search');
        $perPage = min($request->get('per_page', 15), 100);
        $currentPage = $request->get('page', 1);

        $transactions = [];

        // Get coin transactions
        if ($type === 'all' || $type === 'topup') {
            $coinQuery = CoinTransaction::query()->with('user');

            if ($status) {
                $coinQuery->where('status', $status);
            }

            if ($search) {
                $coinQuery->whereHas('user', function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                })->orWhere('reference_code', 'like', "%{$search}%");
            }

            $coinTransactions = $coinQuery->orderBy('created_at', 'desc')->get();

            foreach ($coinTransactions as $transaction) {
                $transactions[] = [
                    'id' => 'coin-'.$transaction->id,
                    'type' => 'topup',
                    'user_id' => $transaction->user_id,
                    'user_name' => $transaction->user->name,
                    'user_email' => $transaction->user->email,
                    'reference_code' => $transaction->reference_code,
                    'amount' => $transaction->amount + $transaction->fee,
                    'coins' => $transaction->coins,
                    'fee' => $transaction->fee,
                    'status' => $transaction->status,
                    'payment_channel' => $transaction->payment_channel,
                    'created_at' => $transaction->created_at->toIso8601String(),
                    'paid_at' => $transaction->paid_at?->toIso8601String(),
                    'expires_at' => $transaction->expires_at?->toIso8601String(),
                ];
            }
        }

        // Get show purchases
        if ($type === 'all' || $type === 'purchase') {
            $purchaseQuery = ShowPurchase::query()->with(['user', 'show']);

            if ($search) {
                $purchaseQuery->whereHas('user', function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                })->orWhereHas('show', function ($q) use ($search) {
                    $q->where('title', 'like', "%{$search}%");
                });
            }

            $showPurchases = $purchaseQuery->orderBy('created_at', 'desc')->get();

            foreach ($showPurchases as $purchase) {
                $transactions[] = [
                    'id' => 'show-'.$purchase->id,
                    'type' => 'purchase',
                    'user_id' => $purchase->user_id,
                    'user_name' => $purchase->user->name,
                    'user_email' => $purchase->user->email,
                    'show_id' => $purchase->show_id,
                    'show_title' => $purchase->show->title ?? ($purchase->show_title ?? 'N/A'),
                    'coins' => $purchase->coin_price,
                    'amount' => $purchase->coin_price * 1000, // Convert to IDR (1 coin = 1000 IDR)
                    'status' => 'success',
                    'created_at' => $purchase->created_at->toIso8601String(),
                ];
            }
        }

        // Sort by created_at descending
        usort($transactions, function ($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });

        // Paginate manually
        $total = count($transactions);
        $offset = ($currentPage - 1) * $perPage;
        $paginatedTransactions = array_slice($transactions, $offset, $perPage);

        return Inertia::render('Admin/Transactions/Index', [
            'transactions' => $paginatedTransactions,
            'pagination' => [
                'current_page' => (int) $currentPage,
                'last_page' => (int) ceil($total / $perPage),
                'per_page' => $perPage,
                'total' => $total,
                'links' => $this->generatePaginationLinks($request, (int) $currentPage, (int) ceil($total / $perPage)),
            ],
            'filters' => [
                'type' => $type ?? 'all',
                'status' => $status ?? '',
                'search' => $search ?? '',
            ],
            'stats' => $this->getTransactionStats(),
        ]);
    }

    /**
     * Generate pagination links.
     */
    private function generatePaginationLinks(Request $request, int $currentPage, int $lastPage): array
    {
        $links = [];
        $queryParams = $request->except('page');
        $baseUrl = '/admin/transactions';

        // Build query string
        $queryString = http_build_query($queryParams);
        $separator = $queryString ? '&' : '?';

        // Previous link
        $prevPage = $currentPage > 1 ? $currentPage - 1 : null;
        if ($prevPage) {
            $prevParams = array_merge($queryParams, ['page' => $prevPage]);
            $links[] = [
                'url' => $baseUrl.'?'.http_build_query($prevParams),
                'label' => '&laquo; Previous',
                'active' => false,
            ];
        } else {
            $links[] = [
                'url' => null,
                'label' => '&laquo; Previous',
                'active' => false,
            ];
        }

        // Page links
        for ($i = 1; $i <= $lastPage; $i++) {
            if ($i == 1 || $i == $lastPage || ($i >= $currentPage - 2 && $i <= $currentPage + 2)) {
                $pageParams = array_merge($queryParams, ['page' => $i]);
                $links[] = [
                    'url' => $baseUrl.'?'.http_build_query($pageParams),
                    'label' => (string) $i,
                    'active' => $i == $currentPage,
                ];
            } elseif ($i == $currentPage - 3 || $i == $currentPage + 3) {
                $links[] = [
                    'url' => null,
                    'label' => '...',
                    'active' => false,
                ];
            }
        }

        // Next link
        $nextPage = $currentPage < $lastPage ? $currentPage + 1 : null;
        if ($nextPage) {
            $nextParams = array_merge($queryParams, ['page' => $nextPage]);
            $links[] = [
                'url' => $baseUrl.'?'.http_build_query($nextParams),
                'label' => 'Next &raquo;',
                'active' => false,
            ];
        } else {
            $links[] = [
                'url' => null,
                'label' => 'Next &raquo;',
                'active' => false,
            ];
        }

        return $links;
    }

    /**
     * Get transaction statistics.
     */
    private function getTransactionStats(): array
    {
        $totalTopups = CoinTransaction::count();
        $successfulTopups = CoinTransaction::where('status', 'success')->count();
        $pendingTopups = CoinTransaction::whereIn('status', ['pending', 'processing'])->count();
        $totalTopupAmount = CoinTransaction::where('status', 'success')->sum('amount');
        $totalTopupFee = CoinTransaction::where('status', 'success')->sum('fee');
        $totalCoinsDistributed = CoinTransaction::where('status', 'success')->sum('coins');

        $totalPurchases = ShowPurchase::count();
        $totalCoinsSpent = ShowPurchase::sum('coin_price');
        $totalPurchaseAmount = $totalCoinsSpent * 1000; // Convert to IDR

        return [
            'total_topups' => $totalTopups,
            'successful_topups' => $successfulTopups,
            'pending_topups' => $pendingTopups,
            'total_topup_amount' => $totalTopupAmount,
            'total_topup_fee' => $totalTopupFee,
            'total_coins_distributed' => $totalCoinsDistributed,
            'total_purchases' => $totalPurchases,
            'total_coins_spent' => $totalCoinsSpent,
            'total_purchase_amount' => $totalPurchaseAmount,
        ];
    }
}
