<?php

namespace App\Http\Controllers;

use App\Helpers\ApiResponse;
use App\Models\MemberProfile;
use App\Models\MembershipPlan;
use App\Models\Payment;
use App\Models\EventRegistration;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\EcaNotification;

class PaymentController extends Controller
{
    // ─────────────────────────────────
    // INITIATE PAYMENT
    // POST /api/payment/initiate
    // ─────────────────────────────────
    public function initiate(Request $request)
{
    $user    = auth()->user();
    $profile = MemberProfile::with('plan')
                ->where('user_id', $user->id)
                ->first();

    if (!$profile) {
        return ApiResponse::error(
            'Member profile not found.', 404
        );
    }

    // ── CHECK ALREADY PAID FIRST ── ← MOVE THIS UP
    $existingPayment = Payment::where('user_id', $user->id)
        ->where('status', 'SUCCESS')
        ->first();

    if ($existingPayment) {
        return ApiResponse::error(
            'You have already completed payment.Your membership is ACTIVE.',
            400
        );
    }

    // ── THEN CHECK STATUS IS APPROVED ── ← MOVE THIS DOWN
    if ($profile->status !== 'APPROVED') {
        return ApiResponse::error(
            'Your membership must be APPROVED before payment. Current status: '
             . $profile->status,
            400
        );
    }

    $plan = $profile->plan;

    if (!$plan) {
        return ApiResponse::error(
            'Membership plan not found.', 404
        );
    }

    // ── Create PENDING payment record ──
    $payment = Payment::create([
        'member_profile_id' => $profile->id,
        'user_id'           => $user->id,
        'plan_id'           => $plan->id,
        'amount'            => $plan->amount,
        'currency'          => 'INR',
        'status'            => 'PENDING',
        'payment_method'    => 'SIMULATED',
        'transaction_id'    => 'TXN-' .
            strtoupper(\Illuminate\Support\Str::random(10)),
        'notes'             => 'Simulated payment - pending completion',
    ]);

    return ApiResponse::success([
        'payment_id'  => (string) $payment->id,
        'amount'      => (string) $plan->amount,
        'currency'    => 'INR',
        'plan_name'   => $plan->name,
        'plan_type'   => $plan->type,
        'member_name' => $user->name,
        'email'       => $user->email,
    ],
    'Payment initiated. Complete payment to activate membership.'
    );
}

    // ─────────────────────────────────
    // VERIFY / COMPLETE PAYMENT
    // POST /api/payment/verify
    // ─────────────────────────────────
    public function verify(Request $request)
    {
        $request->validate([
            'payment_id' => 'required|exists:payments,id',
        ]);

        $user    = auth()->user();
        $payment = Payment::with(['memberProfile', 'plan'])
                    ->where('id', $request->payment_id)
                    ->where('user_id', $user->id)
                    ->first();

        if (!$payment) {
            return ApiResponse::error(
                'Payment not found.', 404
            );
        }

        if ($payment->status === 'SUCCESS') {
            return ApiResponse::error(
                'Payment already completed.', 400
            );
        }

        $profile = $payment->memberProfile;
        $plan    = $payment->plan;

        // ── Generate Membership ID ──
        $membershipId = $this->generateMembershipId($profile);

        // ── Set dates ──
        $joinedDate  = Carbon::now()->toDateString();
        $expiryDate  = $plan->duration_months > 0
            ? Carbon::now()
                ->addMonths($plan->duration_months)
                ->toDateString()
            : null; // LIFE = no expiry

        // ── Update Payment ──
        $payment->update([
            'status'       => 'SUCCESS',
            'membership_id'=> $membershipId,
            'paid_at'      => Carbon::now(),
            'notes'        => 'Payment completed successfully',

            // When Razorpay is ready add:
            // 'razorpay_payment_id' : $request->razorpay_payment_id,
            // 'razorpay_signature'  : $request->razorpay_signature,
        ]);

        // ── Update Member Profile ──
        $profile->update([
            'status'        => 'ACTIVE',
            'membership_id' => $membershipId,
            'joined_date'   => $joinedDate,
            'expiry_date'   => $expiryDate,
            
        ]);

        // ── Notify member of successful payment ──
EcaNotification::send(
    $user->id,
    'Membership Activated! 🎉',
    'Your payment was successful. Membership ID: ' . $membershipId . '. Welcome to ECA!',
    'PAYMENT'
);

        // ── Send Success Email ──
        try {
            \Illuminate\Support\Facades\Mail::to($user->email)
                ->send(new \App\Mail\PaymentSuccessMail(
                    memberName   : $user->name,
                    membershipId : $membershipId,
                    planName     : $plan->name,
                    planType     : $plan->type,
                    amount       : number_format(
                        $payment->amount, 0
                    ),
                    joinedDate   : $joinedDate,
                    expiryDate   : $expiryDate,
                    unitName     : $profile->unit->name
                        ?? 'ECA Unit',
                ));
        } catch (\Exception $e) {
            // Don't fail if email fails
            \Illuminate\Support\Facades\Log::error(
                'Payment success email failed: ' .
                $e->getMessage()
            );
        }

        return ApiResponse::success([
            'membership_id'  => $membershipId,
            'status'         => 'ACTIVE',
            'plan_name'      => $plan->name,
            'plan_type'      => $plan->type,
            'amount_paid'    => (string) $payment->amount,
            'joined_date'    => $joinedDate,
            'expiry_date'    => $expiryDate ?? 'Lifetime',
            'paid_at'        => $payment->paid_at,
        ],
        'Payment successful! Welcome to ECA! 🎉'
        );
    }

    // ─────────────────────────────────
    // PAYMENT HISTORY
    // GET /api/payment/history
    // ─────────────────────────────────
    public function history()
    {
        $user     = auth()->user();
        $payments = Payment::with('plan')
                    ->where('user_id', $user->id)
                    ->latest()
                    ->get();

        $data = $payments->map(function ($payment) {
            return [
                'id'            => (string) $payment->id,
                'plan_name'     => $payment->plan->name ?? '—',
                'plan_type'     => $payment->plan->type ?? '—',
                'amount'        => (string) $payment->amount,
                'currency'      => $payment->currency,
                'status'        => $payment->status,
                'membership_id' => $payment->membership_id ?? '—',
                'transaction_id'=> $payment->transaction_id ?? '—',
                'paid_at'       => $payment->paid_at
                    ? $payment->paid_at->format('d M Y h:i A')
                    : '—',
                'created_at'    => $payment->created_at
                    ->format('d M Y'),
            ];
        });

        return ApiResponse::success(
            $data,
            'Payment history fetched successfully'
        );
    }

    // ─────────────────────────────────
    // GENERATE MEMBERSHIP ID (private)
    // Format: ECA-KL-KZD-2026-001
    // ─────────────────────────────────
    private function generateMembershipId(
        MemberProfile $profile
    ): string {
        $profile->loadMissing(['state', 'district']);

        // State code (first 2 letters)
        $stateCode = strtoupper(
            substr($profile->state->name ?? 'XX', 0, 2)
        );

        // District code (first 3 letters)
        $districtCode = strtoupper(
            substr($profile->district->name ?? 'XXX', 0, 3)
        );

        $year = Carbon::now()->year;

        // Get next serial number for this year
        $lastPayment = Payment::where('status', 'SUCCESS')
            ->whereYear('paid_at', $year)
            ->whereNotNull('membership_id')
            ->orderBy('id', 'desc')
            ->first();

        if ($lastPayment && $lastPayment->membership_id) {
            // Extract serial from last ID
            $parts  = explode('-', $lastPayment->membership_id);
            $serial = (int) end($parts) + 1;
        } else {
            $serial = 1;
        }

        $serialFormatted = str_pad($serial, 3, '0', STR_PAD_LEFT);

        return "ECA-{$stateCode}-{$districtCode}-{$year}-{$serialFormatted}";
    }

    // ─────────────────────────────────
// INITIATE EVENT PAYMENT
// POST /api/events/payment/initiate
// ─────────────────────────────────
public function initiateEventPayment(Request $request)
{
    $request->validate([
        'registration_id' => 'required|exists:event_registrations,id',
    ]);

    $user         = auth()->user();
    $registration = EventRegistration::with(['event', 'memberProfile'])
                    ->where('id', $request->registration_id)
                    ->where('user_id', $user->id)
                    ->first();

    if (!$registration) {
        return ApiResponse::error(
            'Registration not found.', 404
        );
    }

    // ── Check is PAID event ──
    if ($registration->event->ticket_type === 'FREE') {
        return ApiResponse::error(
            'This is a FREE event. No payment required.', 400
        );
    }

    // ── Check already paid ──
    if ($registration->payment_status === 'PAID') {
        return ApiResponse::error(
            'You have already paid for this event.', 400
        );
    }

    // ── Check existing pending payment ──
    $existingPayment = Payment::where('user_id', $user->id)
        ->where('event_registration_id', $registration->id)
        ->where('status', 'PENDING')
        ->first();

    if ($existingPayment) {
        return ApiResponse::success([
            'payment_id'      => (string) $existingPayment->id,
            'amount'          => (string) $existingPayment->amount,
            'currency'        => 'INR',
            'event_title'     => $registration->event->title,
            'event_date'      => $registration->event->event_date->format('d M Y'),
            'ticket_number'   => $registration->ticket_number,
            'member_name'     => $user->name,
        ], 'Existing pending payment found. Complete payment.');
    }

    // ── Create payment record ──
    $payment = Payment::create([
        'member_profile_id'    => $registration->member_profile_id,
        'event_registration_id'=> $registration->id,
        'user_id'              => $user->id,
        'plan_id'              => $registration->memberProfile->plan_id,
        'amount'               => $registration->event->ticket_price,
        'currency'             => 'INR',
        'status'               => 'PENDING',
        'payment_method'       => 'SIMULATED',
        'payment_type'         => 'EVENT',
        'transaction_id'       => 'EVT-TXN-' . strtoupper(\Illuminate\Support\Str::random(10)),
        'notes'                => 'Event ticket payment for ' . $registration->event->title,
    ]);

    return ApiResponse::success([
        'payment_id'    => (string) $payment->id,
        'amount'        => (string) $payment->amount,
        'currency'      => 'INR',
        'event_title'   => $registration->event->title,
        'event_date'    => $registration->event->event_date->format('d M Y'),
        'event_time'    => $registration->event->event_time,
        'location'      => $registration->event->location,
        'ticket_number' => $registration->ticket_number,
        'member_name'   => $user->name,
        'email'         => $user->email,
    ], 'Event payment initiated. Complete payment to confirm ticket.');
}

// ─────────────────────────────────
// VERIFY EVENT PAYMENT
// POST /api/events/payment/verify
// ─────────────────────────────────
public function verifyEventPayment(Request $request)
{
    $request->validate([
        'payment_id' => 'required|exists:payments,id',
    ]);

    $user    = auth()->user();
    $payment = Payment::with(['eventRegistration.event'])
                ->where('id', $request->payment_id)
                ->where('user_id', $user->id)
                ->where('payment_type', 'EVENT')
                ->first();

    if (!$payment) {
        return ApiResponse::error(
            'Payment not found.', 404
        );
    }

    if ($payment->status === 'SUCCESS') {
        return ApiResponse::error(
            'Payment already completed.', 400
        );
    }

    $registration = $payment->eventRegistration;
    $event        = $registration->event;

    // ── Update Payment ──
    $payment->update([
        'status'  => 'SUCCESS',
        'paid_at' => Carbon::now(),
        'notes'   => 'Event payment completed for ' . $event->title,
    ]);

    // ── Update Registration payment status ──
    $registration->update([
        'payment_status' => 'PAID',
    ]);

    // ── Send confirmation email ──
    try {
        \Illuminate\Support\Facades\Mail::to($user->email)
            ->send(new \App\Mail\EventPaymentSuccessMail(
                memberName   : $user->name,
                eventTitle   : $event->title,
                eventDate    : $event->event_date->format('d M Y'),
                eventTime    : $event->event_time,
                location     : $event->location ?? 'Online',
                ticketNumber : $registration->ticket_number,
                amount       : number_format($payment->amount, 0),
            ));
    } catch (\Exception $e) {
        \Illuminate\Support\Facades\Log::error(
            'Event payment email failed: ' . $e->getMessage()
        );
    }

    return ApiResponse::success([
        'ticket_number'  => $registration->ticket_number,
        'event_title'    => $event->title,
        'event_date'     => $event->event_date->format('d M Y'),
        'event_time'     => $event->event_time,
        'location'       => $event->location ?? 'Online',
        'payment_status' => 'PAID',
        'amount_paid'    => (string) $payment->amount,
        'paid_at'        => $payment->paid_at->format('d M Y h:i A'),
    ], 'Event payment successful! Your ticket is confirmed. 🎫');
}
// ─────────────────────────────────
// RENEWAL STATUS
// GET /api/member/renewal-status
// ─────────────────────────────────
public function renewalStatus()
{
    $user    = auth()->user();
    $profile = MemberProfile::with('plan')
                ->where('user_id', $user->id)
                ->first();

    if (!$profile) {
        return ApiResponse::error('Profile not found.', 404);
    }

    // LIFE members don't need renewal
    if ($profile->membership_type === 'LIFE') {
        return ApiResponse::success([
            'needs_renewal'  => false,
            'membership_type'=> 'LIFE',
            'message'        => 'Life membership never expires.',
        ], 'Renewal status fetched');
    }

    $expiryDate   = $profile->expiry_date
        ? \Carbon\Carbon::parse($profile->expiry_date)
        : null;
    $daysToExpiry = $expiryDate
        ? max(0, \Carbon\Carbon::now()->diffInDays(
            $expiryDate, false
          ))
        : null;
    $isExpired    = $expiryDate
        ? $expiryDate->isPast()
        : false;
    $expiringSoon = $daysToExpiry !== null && $daysToExpiry <= 30;

    return ApiResponse::success([
        'needs_renewal'   => $isExpired || $expiringSoon,
        'is_expired'      => $isExpired,
        'expiring_soon'   => $expiringSoon,
        'days_to_expiry'  => $daysToExpiry,
        'expiry_date'     => $profile->expiry_date
            ? \Carbon\Carbon::parse($profile->expiry_date)
                ->format('d M Y')
            : null,
        'membership_type' => $profile->membership_type,
        'plan_name'       => $profile->plan->name ?? '—',
        'renewal_amount'  => (string) ($profile->plan->amount ?? 0),
        'status'          => $profile->status,
    ], 'Renewal status fetched');
}

// ─────────────────────────────────
// RENEW MEMBERSHIP
// POST /api/payment/renew
// ─────────────────────────────────
public function renew(Request $request)
{
    $user    = auth()->user();
    $profile = MemberProfile::with('plan')
                ->where('user_id', $user->id)
                ->first();

    if (!$profile) {
        return ApiResponse::error('Profile not found.', 404);
    }

    // Only ANNUAL members can renew
    if ($profile->membership_type === 'LIFE') {
        return ApiResponse::error(
            'Life members do not need renewal.', 400
        );
    }

    // Must be ACTIVE or EXPIRED to renew
    if (!in_array($profile->status, ['ACTIVE', 'EXPIRED'])) {
        return ApiResponse::error(
            'Only ACTIVE or EXPIRED members can renew. Current status: ' . $profile->status,
            400
        );
    }

    $plan = $profile->plan;

    // Create renewal payment
    $payment = Payment::create([
        'member_profile_id' => $profile->id,
        'user_id'           => $user->id,
        'plan_id'           => $plan->id,
        'amount'            => $plan->amount,
        'currency'          => 'INR',
        'status'            => 'PENDING',
        'payment_method'    => 'SIMULATED',
        'payment_type'      => 'MEMBERSHIP',
        'transaction_id'    => 'RNW-' . strtoupper(Str::random(10)),
        'notes'             => 'Membership renewal payment',
    ]);

    return ApiResponse::success([
        'payment_id'  => (string) $payment->id,
        'amount'      => (string) $plan->amount,
        'currency'    => 'INR',
        'plan_name'   => $plan->name,
        'member_name' => $user->name,
    ], 'Renewal payment initiated. Complete payment to extend membership.');
}
}