<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Receipt;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class ReceiptController extends Controller
{
    /**
     * Display receipt management page
     */
    public function index()
    {
        $receipts = Receipt::with('creator')
            ->orderBy('created_at', 'desc')
            ->paginate(25);

        $title = 'Receipt Generator';

        return view('admin.receipts.index', compact('receipts', 'title'));
    }

    /**
     * Show form to create new receipt
     */
    public function create()
    {
        $cryptocurrencies = [
            'BTC' => 'Bitcoin',
            'ETH' => 'Ethereum',
            'USDT' => 'Tether USD',
            'BNB' => 'Binance Coin',
            'ADA' => 'Cardano',
            'XRP' => 'Ripple',
            'SOL' => 'Solana',
            'DOT' => 'Polkadot',
            'DOGE' => 'Dogecoin',
            'MATIC' => 'Polygon',
            'LTC' => 'Litecoin',
            'BCH' => 'Bitcoin Cash',
            'LINK' => 'Chainlink',
            'UNI' => 'Uniswap',
            'ATOM' => 'Cosmos'
        ];

        $networks = [
            'BTC' => 'Bitcoin Network',
            'ETH' => 'Ethereum (ERC-20)',
            'BSC' => 'Binance Smart Chain (BEP-20)',
            'TRX' => 'Tron (TRC-20)',
            'MATIC' => 'Polygon Network',
            'SOL' => 'Solana Network',
            'AVAX' => 'Avalanche Network'
        ];

        $templates = [
            'bybit' => 'Bybit Style',
            'binance' => 'Binance Style',
            'coinbase' => 'Coinbase Style'
        ];

        $title = 'Generate New Receipt';

        return view('admin.receipts.create', compact('cryptocurrencies', 'networks', 'templates', 'title'));
    }

    /**
     * Store new receipt
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_name' => 'required|string|max:255',
            'user_email' => 'required|email|max:255',
            'amount' => 'required|numeric|min:0',
            'cryptocurrency' => 'required|string|max:10',
            'wallet_address' => 'required|string|max:255',
            'transaction_type' => 'required|in:deposit,withdrawal,trade,transfer,purchase,sale',
            'template_type' => 'required|in:bybit,binance,coinbase',
            'transaction_date' => 'required|date',
            'network' => 'nullable|string|max:50',
            'transaction_hash' => 'nullable|string|max:255',
            'fee_amount' => 'nullable|numeric|min:0',
            'fee_currency' => 'nullable|string|max:10',
            'notes' => 'nullable|string|max:1000'
        ]);

        // Get the authenticated admin ID
        $adminId = Auth::guard('admin')->id();

        // If no admin is authenticated, try to get the first admin or use a default
        if (!$adminId) {
            $firstAdmin = \App\Models\Admin::first();
            $adminId = $firstAdmin ? $firstAdmin->id : 1;
        }

        $receipt = Receipt::create([
            'receipt_number' => Receipt::generateReceiptNumber($request->template_type),
            'user_name' => $request->user_name,
            'user_email' => $request->user_email,
            'amount' => $request->amount,
            'cryptocurrency' => strtoupper($request->cryptocurrency),
            'wallet_address' => $request->wallet_address,
            'transaction_type' => $request->transaction_type,
            'template_type' => $request->template_type,
            'transaction_date' => Carbon::parse($request->transaction_date),
            'network' => $request->network,
            'transaction_hash' => $request->transaction_hash,
            'fee_amount' => $request->fee_amount ?? 0,
            'fee_currency' => $request->fee_currency ? strtoupper($request->fee_currency) : null,
            'notes' => $request->notes,
            'status' => 'completed',
            'created_by' => $adminId
        ]);

        return redirect()->route('admin.receipts.show', $receipt->id)
            ->with('success', 'Receipt generated successfully!');
    }

    /**
     * Show receipt details
     */
    public function show(Receipt $receipt)
    {
        $title = 'Receipt Details - ' . $receipt->receipt_number;

        return view('admin.receipts.show', compact('receipt', 'title'));
    }

    /**
     * Generate PDF receipt
     */
    public function generatePDF(Receipt $receipt)
    {
        $templateView = match($receipt->template_type) {
            'bybit' => 'admin.receipts.templates.bybit',
            'binance' => 'admin.receipts.templates.binance',
            'coinbase' => 'admin.receipts.templates.coinbase',
            default => 'admin.receipts.templates.bybit'
        };

        // For now, return the HTML view. You can add PDF generation later
        return view($templateView, compact('receipt'));
    }

    /**
     * Delete receipt
     */
    public function destroy(Receipt $receipt)
    {
        $receipt->delete();

        return redirect()->route('admin.receipts.index')
            ->with('success', 'Receipt deleted successfully!');
    }
}
