<?php

namespace App\Http\Controllers;

use App\Mail\AdminNewLeadMail;
use App\Mail\PaymentReceivedMail;
use App\Mail\LiteTemplateDeliveryMail;
use App\Models\Lead;
use App\Models\Payment;
use App\Services\QPayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class PaymentController extends Controller
{
    protected QPayService $qpay;

    protected array $tierPrices = [
        'lite'     => 290000,
        'standard' => 890000,
        'pro'      => 2490000,
    ];

    public function __construct(QPayService $qpay)
    {
        $this->qpay = $qpay;
    }

    /**
     * Захиалга үүсгэн QPay invoice үүсгэх (TemplatesController-ээс дуудах эсвэл шууд).
     */
    public function create(Request $request)
    {
        $data = $request->validate([
            'tier'          => 'required|in:lite,standard,pro',
            'name'          => 'required|string|max:255',
            'email'         => 'required|email|max:255',
            'phone'         => 'required|string|max:50',
            'business_name' => 'nullable|string|max:255',
        ]);

        // Lead үүсгэх/шинэчлэх
        $lead = Lead::updateOrCreate(
            ['email' => $data['email']],
            [
                'name'          => $data['name'],
                'phone'         => $data['phone'],
                'business_name' => $data['business_name'] ?? null,
                'source'        => 'template_order',
                'status'        => 'new',
                'notes'         => "QPay захиалга: " . strtoupper($data['tier']),
            ]
        );

        // Payment record
        $payment = Payment::create([
            'lead_id'  => $lead->id,
            'tier'     => $data['tier'],
            'amount'   => $this->tierPrices[$data['tier']],
            'currency' => 'MNT',
            'status'   => 'pending',
        ]);

        // QPay invoice үүсгэх
        if (! $this->qpay->isConfigured()) {
            return response()->json([
                'ok' => false,
                'message' => 'QPay тохиргооноогүй байна. info@nsma.mn руу шууд холбогдоно уу.',
                'fallback_email' => 'info@nsma.mn',
            ], 503);
        }

        $invoice = $this->qpay->createInvoice($payment);
        if (! $invoice) {
            return response()->json([
                'ok' => false,
                'message' => 'QPay invoice үүсгэхэд алдаа гарлаа. Дахин оролдох эсвэл info@nsma.mn руу холбогдоно уу.',
            ], 502);
        }

        $payment->update([
            'qpay_invoice_id' => $invoice['invoice_id'],
            'qpay_qr_text'    => $invoice['qr_text'],
            'qpay_qr_image'   => $invoice['qr_image'],
            'qpay_urls'       => $invoice['urls'],
        ]);

        if ($request->wantsJson()) {
            return response()->json([
                'ok' => true,
                'payment_id' => $payment->id,
                'redirect'   => route('payment.show', $payment->id),
            ]);
        }

        return redirect()->route('payment.show', $payment->id);
    }

    /**
     * Төлбөрийн QR хуудас (founder QR-ыг сканнаж төлнө).
     */
    public function show(Payment $payment)
    {
        return view('frontend.payment', compact('payment'));
    }

    /**
     * Polling endpoint — статусыг шалгана.
     */
    public function status(Payment $payment)
    {
        // Local статус paid бол шууд буцаа
        if ($payment->isPaid()) {
            return response()->json(['status' => 'paid', 'paid_at' => $payment->paid_at]);
        }

        // QPay-аас шалгах
        if ($payment->qpay_invoice_id) {
            $check = $this->qpay->checkPayment($payment->qpay_invoice_id);
            if ($check && $check['paid']) {
                $this->markAsPaid($payment, $check['paid_row'] ?? []);
            }
        }
        return response()->json(['status' => $payment->fresh()->status]);
    }

    /**
     * QPay webhook — төлбөр амжилттай хийгдсэн үед QPay дуудна.
     */
    public function webhook(Request $request)
    {
        $paymentId = $request->query('payment_id');
        $payment = Payment::find($paymentId);
        if (! $payment) {
            Log::warning('QPay webhook: payment not found', ['payment_id' => $paymentId]);
            return response()->json(['ok' => false], 404);
        }

        // Webhook ирсэн боловч double-check шаардлагатай
        if ($payment->qpay_invoice_id) {
            $check = $this->qpay->checkPayment($payment->qpay_invoice_id);
            if ($check && $check['paid']) {
                $this->markAsPaid($payment, $check['paid_row'] ?? [], $request->all());
            }
        }

        return response()->json(['ok' => true]);
    }

    /**
     * Payment-ыг paid гэж тэмдэглэн delivery-г trigger хийх.
     */
    protected function markAsPaid(Payment $payment, array $paidRow, array $callback = []): void
    {
        if ($payment->isPaid()) return;

        $payment->update([
            'status'       => 'paid',
            'paid_at'      => now(),
            'paid_amount'  => $paidRow['payment_amount'] ?? $payment->amount,
            'paid_method'  => $paidRow['payment_wallet'] ?? 'qpay',
            'raw_callback' => $callback,
        ]);

        $payment->lead?->update(['status' => 'converted']);

        // Auto-delivery үе шат
        try {
            if ($payment->tier === 'lite') {
                // Lite — шууд PDF email явуулна
                Mail::to($payment->lead->email)->queue(new LiteTemplateDeliveryMail($payment));
            }

            // Бүх tier-д төлбөр амжилттай confirmation
            Mail::to($payment->lead->email)->queue(new PaymentReceivedMail($payment));

            // Admin notification
            Mail::to(config('mail.admin_email', 'info@nsma.mn'))->queue(new AdminNewLeadMail($payment->lead));
        } catch (\Exception $e) {
            Log::error('Payment delivery email failed', ['msg' => $e->getMessage()]);
        }
    }
}
