<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use App\Http\Requests\PaymentCreateRequest;
use App\Http\Requests\PaymentVerifyRequest;
use Illuminate\Support\Facades\DB;
use App\Services\Payments\PaymentService;

class PaymentsController extends Controller
{
    public function create(PaymentCreateRequest $request): JsonResponse
    {
        $planKey = $request->validated()['plan'];
        $userId = optional($request->user())->id ?? 239053159; // TODO: map from Telegram user when available
        $svc = app(PaymentService::class);
        $res = $svc->createPending($userId, $planKey);
        // Track UpgradeClick
        try { \App\Services\Analytics\EventBus::track($userId, 'UpgradeClick', ['plan' => $planKey]); } catch (\Throwable) {}
        return response()->json($res);
    }

    public function verify(PaymentVerifyRequest $request): JsonResponse
    {
        $authority = $request->validated()['authority'];
        $status = $request->validated()['status'] ?? null; // OK | NOK
        // Idempotent: if already verified by authority
        $existing = DB::table('payments')->where('ref', $authority)->where('status','ok')->first();
        if ($existing) {
            return response()->json(['status' => 'ok','payment_id' => $existing->id,'ref'=>$authority,'subscription'=>['status'=>'active']]);
        }
        // Find pending by authority
        $payment = DB::table('payments')->where('status','pending')->where('ref',$authority)->latest('id')->first();
        if (!$payment) {
            return response()->json(['status' => 'failed','payment_id' => 0,'ref'=>$authority,'subscription'=>null]);
        }
        // Verify via gateway in sandbox (best effort)
        $verified = false;
        try {
            if (strtoupper((string)$status) === 'OK') {
                $verified = true;
            } else {
                $res = app(PaymentService::class)->verify($authority, (int) $payment->amount);
                $verified = (bool)($res['ok'] ?? false);
            }
        } catch (\Throwable) {}
        if (!$verified) {
            return response()->json(['status' => 'failed','payment_id' => (int)$payment->id,'ref'=>$authority,'subscription'=>null]);
        }
        DB::table('payments')->where('id',$payment->id)->update(['status'=>'ok','updated_at'=>now()]);
        $sub = DB::table('subscriptions')->where('user_id',$payment->user_id)->latest('id')->first();
        $plan = DB::table('plans')->where('id',$payment->plan_id)->first();
        $starts = now();
        $ends = now()->copy()->addDays($plan?->duration_days ?? 30);
        if ($sub) {
            DB::table('subscriptions')->where('id',$sub->id)->update(['status'=>'active','starts_at'=>$starts,'ends_at'=>$ends,'updated_at'=>now()]);
        } else {
            DB::table('subscriptions')->insert([
                'user_id' => $payment->user_id,
                'plan_id' => $payment->plan_id,
                'plan' => $plan?->key ?? 'basic',
                'status' => 'active',
                'starts_at' => $starts,
                'ends_at' => $ends,
                'created_at' => now(), 'updated_at' => now(),
            ]);
        }
        // Emit UpgradeSuccess event if possible
        try {
            \App\Services\Analytics\EventBus::track($payment->user_id, 'UpgradeSuccess', [
                'plan' => $plan?->key,
                'amount' => $payment->amount,
                'authority' => $authority,
            ]);
        } catch (\Throwable $e) {
            // swallow
        }
        return response()->json(['status' => 'ok', 'payment_id' => $payment->id, 'ref' => $authority, 'subscription' => ['status'=>'active']]);
    }

    public function reconcile(Request $request): JsonResponse
    {
        // Close stale pending payments (older than 24h) as failed
        $stale = DB::table('payments')->where('status','pending')->where('created_at','<', now()->subDay());
        $count = (clone $stale)->count();
        $stale->update(['status'=>'failed','updated_at'=>now()]);
        return response()->json(['reconciled' => 0, 'failed' => $count]);
    }
}
