<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\LockerPayment;
use App\Models\LockerRegistration;
use App\Models\LockerRegistrationItem;
use App\Models\MembershipPlan;
use App\Models\Payment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class PaymentController extends Controller
{
    /**
     * Show payment page for a client
     */
    public function index($clientId)
    {
        $client = Client::with([
            'lockerRegistrations.locker',
            'lockerRegistrations.membershipPlan',
            'membershipPlan',
            'customerMembers'
        ])->findOrFail($clientId);

        // Get pending payments
        $pendingPayments = LockerPayment::where('client_id', $clientId)
            ->where('payment_status', 'pending')
            ->with(['lockerRegistration.locker', 'membershipPlan'])
            ->get();

        // Get payment history
        $paymentHistory = LockerPayment::where('client_id', $clientId)
            ->whereIn('payment_status', ['paid', 'refunded'])
            ->with(['lockerRegistration.locker', 'membershipPlan'])
            ->orderBy('created_at', 'desc')
            ->get();

        // Calculate totals
        $totalPending = $pendingPayments->sum('amount');
        $totalPaid = $paymentHistory->sum('amount');

        return view('clients.payment', compact(
            'client',
            'pendingPayments',
            'paymentHistory',
            'totalPending',
            'totalPaid'
        ));
    }

    /**
     * Process payment for locker registration
     */
    public function processPayment(Request $request, $clientId)
    {
        $validator = Validator::make($request->all(), [
            'payment_method' => 'required|in:cash,card,debit_card,bank_transfer,online,cheque,fpx',
            'payment_type' => 'required|in:registration_fee,rent,deposit,renewal,penalty,maintenance',
            'amount' => 'required|numeric|min:0.01',
            'payment_date' => 'required|date',
            'notes' => 'nullable|string|max:500',
            'locker_registration_id' => 'required|exists:locker_registrations,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        try {
            DB::beginTransaction();

            $client = Client::findOrFail($clientId);
            $lockerRegistration = LockerRegistration::findOrFail($request->locker_registration_id);

            // Create payment record
            $payment = LockerPayment::create([
                'client_id' => $clientId,
                'locker_registration_id' => $request->locker_registration_id,
                'membership_plan_id' => $lockerRegistration->membership_plan_id,
                'amount' => $request->amount,
                'payment_type' => $request->payment_type,
                'payment_method' => $request->payment_method,
                'payment_status' => 'paid',
                'payment_date' => $request->payment_date,
                'transaction_id' => 'TXN' . time() . rand(1000, 9999),
                'invoice_number' => 'INV' . date('Y') . str_pad($clientId, 6, '0', STR_PAD_LEFT),
                'tax_amount' => $request->tax_amount ?? 0,
                'discount_amount' => $request->discount_amount ?? 0,
                'notes' => $request->notes,
            ]);

            // Update locker registration status to Active if payment is for registration
            if ($request->payment_type === 'registration_fee' || $request->payment_type === 'rent') {
                $lockerRegistration->update(['status' => 'Active']);

                // Update locker status to Active
                $lockerRegistration->locker()->update(['status' => 'Occupied']);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Payment processed successfully',
                'payment' => $payment->load(['lockerRegistration.locker', 'membershipPlan'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Error processing payment: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get pending payments for a client
     */
    public function getPendingPayments($clientId)
    {
        $pendingPayments = LockerPayment::where('client_id', $clientId)
            ->where('payment_status', 'pending')
            ->with(['lockerRegistration.locker', 'membershipPlan'])
            ->get();

        return response()->json([
            'success' => true,
            'payments' => $pendingPayments
        ]);
    }

    /**
     * Create pending payment for locker registration
     */
    public function createPendingPayment(Request $request, $clientId)
    {
        $validator = Validator::make($request->all(), [
            'locker_registration_id' => 'required|exists:locker_registrations,id',
            'amount' => 'required|numeric|min:0.01',
            'payment_type' => 'required|in:registration_fee,rent,deposit,renewal,penalty,maintenance',
            'due_date' => 'required|date|after:today',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        try {
            $lockerRegistration = LockerRegistration::findOrFail($request->locker_registration_id);

            $payment = LockerPayment::create([
                'client_id' => $clientId,
                'locker_registration_id' => $request->locker_registration_id,
                'membership_plan_id' => $lockerRegistration->membership_plan_id,
                'amount' => $request->amount,
                'payment_type' => $request->payment_type,
                'payment_method' => 'pending',
                'payment_status' => 'pending',
                'due_date' => $request->due_date,
                'invoice_number' => 'INV' . date('Y') . str_pad($clientId, 6, '0', STR_PAD_LEFT),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Pending payment created successfully',
                'payment' => $payment->load(['lockerRegistration.locker', 'membershipPlan'])
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating pending payment: ' . $e->getMessage()
            ], 500);
        }
    }



    // public function processRenewal(Request $request, $clientId, $registrationId)
    // {
    //     $validator = Validator::make($request->all(), [
    //         'locker_registration_id' => 'required|exists:locker_registrations,id',
    //         'membership_plan_id' => 'required|exists:membership_plans,id',
    //         'payment_method' => 'required|in:cash,card,bank_transfer,online,cheque',
    //         'payment_date' => 'required|date',
    //         'contract_start_date' => 'required|date',
    //         'contract_end_date' => 'required|date|after_or_equal:contract_start_date',
    //         'amount' => 'required|numeric|min:0.01',
    //         'tax_amount' => 'required|numeric|min:0',
    //         'payment_type' => 'required|in:renewal',
    //     ]);

    //     if ($validator->fails()) {
    //         return redirect()->back()->withErrors($validator)->withInput();
    //     }

    //     DB::beginTransaction();

    //     try {
    //         $client = Client::findOrFail($clientId);
    //         $oldRegistration = LockerRegistration::with(['items', 'locker'])->findOrFail($registrationId);

    //         if ((int) $oldRegistration->client_id !== (int) $clientId) {
    //             abort(404);
    //         }

    //         $oldRegistration->update(['status' => 'Expired']);
    //         foreach ($oldRegistration->items as $item) {
    //             $item->update(['status' => 'expired']);
    //         }

    //         $paymentMethod = $request->payment_method;
    //         if ($paymentMethod === 'debit_card') {
    //             $paymentMethod = 'card';
    //         } elseif ($paymentMethod === 'fpx') {
    //             $paymentMethod = 'online';
    //         }

    //         $newRegistration = LockerRegistration::create([
    //             'client_id' => $client->id,
    //             'auth_count' => $oldRegistration->auth_count,
    //             'locker_password' => $oldRegistration->locker_password,
    //             'registration_date' => now()->toDateString(),
    //             'payment_terms' => $request->membership_plan_id,
    //             'commission_used' => $oldRegistration->commission_used,
    //             'safebox_count' => $oldRegistration->safebox_count,
    //             'contract_start_date' => $request->contract_start_date,
    //             'contract_end_date' => $request->contract_end_date,
    //             'stamping_fee' => $oldRegistration->stamping_fee,
    //             'key_deposit' => $oldRegistration->key_deposit,
    //             'insurance_charges' => $oldRegistration->insurance_charges,
    //             'discount_amount' => $oldRegistration->discount_amount,
    //             'tax_amount' => $request->tax_amount,
    //             'referred_member_by' => $oldRegistration->referred_member_by,
    //             'referred_commission' => $oldRegistration->referred_commission,
    //             'status' => 'Active',
    //         ]);

    //         if ($oldRegistration->items->count() > 0) {
    //             foreach ($oldRegistration->items as $item) {
    //                 LockerRegistrationItem::create([
    //                     'registration_id' => $newRegistration->id,
    //                     'locker_id' => $item->locker_id,
    //                     'locker_number' => $item->locker_number,
    //                     'size' => $item->size,
    //                     'type' => $item->type,
    //                     'locker_group' => $item->locker_group,
    //                     'locker_position' => $item->locker_position,
    //                     'start_date' => $request->contract_start_date,
    //                     'end_date' => $request->contract_end_date,
    //                     'amount' => $item->amount,
    //                     'status' => 'active',
    //                     'added_at' => now(),
    //                 ]);
    //             }
    //         } elseif ($oldRegistration->locker) {
    //             LockerRegistrationItem::create([
    //                 'registration_id' => $newRegistration->id,
    //                 'locker_id' => $oldRegistration->locker->id,
    //                 'locker_number' => $oldRegistration->locker->locker_number,
    //                 'size' => $oldRegistration->locker->locker_size,
    //                 'type' => $oldRegistration->locker->locker_type,
    //                 'locker_group' => $oldRegistration->locker->locker_group ?? null,
    //                 'locker_position' => $oldRegistration->locker->locker_position ?? null,
    //                 'start_date' => $request->contract_start_date,
    //                 'end_date' => $request->contract_end_date,
    //                 'amount' => $oldRegistration->locker_amount ?? 0,
    //                 'status' => 'active',
    //                 'added_at' => now(),
    //             ]);
    //         }

    //         Payment::create([
    //             'registration_id' => $newRegistration->id,
    //             'payment_mode' => $paymentMethod,
    //             'total_amount' => $request->amount,
    //             'paid_amount' => $request->amount,
    //             'balance_amount' => 0,
    //             'payment_date' => $request->payment_date,
    //             'status' => 'paid',
    //             'transaction_id' => 'TXN' . time() . rand(1000, 9999),
    //             'notes' => $request->notes ?? null,
    //         ]);

    //         DB::commit();

    //         return redirect()->route('customers.show', $client->id)
    //             ->with('success', 'Renewal completed successfully and payment saved.');
    //     } catch (\Exception $e) {
    //         DB::rollBack();
    //         \Log::error('Renewal processing failed', [
    //             'client_id' => $clientId,
    //             'registration_id' => $registrationId,
    //             'request' => $request->all(),
    //             'exception' => $e,
    //         ]);
    //         $errorMessage = $e->getMessage() ?: 'An unexpected error occurred. Please try again.';
    //         return redirect()->back()->with('error', 'Unable to process renewal: ' . $errorMessage);
    //     }
    // }

    public function processRenewal(Request $request, $clientId, $registrationId)
    {
        $validator = Validator::make($request->all(), [
            'locker_registration_id' => 'required|exists:locker_registrations,id',
            'membership_plan_id' => 'required|exists:membership_plans,id',
            'payment_method' => 'required|in:cash,card,bank_transfer,online,cheque,debit_card,fpx',
            'payment_date' => 'required|date',
            'contract_start_date' => 'required|date',
            'contract_end_date' => 'required|date|after_or_equal:contract_start_date',
            'amount' => 'required|numeric|min:0.01',
            'tax_amount' => 'required|numeric|min:0',
            'payment_type' => 'required|in:renewal',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        DB::beginTransaction();

        try {
            // 1. Fetch data
            $client = Client::findOrFail($clientId);
            $oldRegistration = LockerRegistration::with(['items', 'locker'])->findOrFail($registrationId);

            // Safety check
            if ((int)$oldRegistration->client_id !== (int)$clientId) {
                abort(404);
            }

            if ($oldRegistration->status !== 'Active') {
                throw new \Exception('Only active registrations can be renewed');
            }

            // Normalize payment method
            $paymentMethod = $request->payment_method;
            if ($paymentMethod === 'debit_card') {
                $paymentMethod = 'card';
            } elseif ($paymentMethod === 'fpx') {
                $paymentMethod = 'online';
            }

            // 2. CREATE NEW REGISTRATION FIRST
            $newRegistration = LockerRegistration::create([
                'client_id' => $client->id,
                'auth_count' => $oldRegistration->auth_count,
                'locker_password' => $oldRegistration->locker_password,
                'registration_date' => now()->toDateString(),
                'payment_terms' => $request->membership_plan_id,
                'commission_used' => $oldRegistration->commission_used,
                'safebox_count' => $oldRegistration->safebox_count,
                'contract_start_date' => $request->contract_start_date,
                'contract_end_date' => $request->contract_end_date,
                'stamping_fee' => $oldRegistration->stamping_fee,
                'key_deposit' => $oldRegistration->key_deposit,
                'insurance_charges' => $oldRegistration->insurance_charges,
                'discount_amount' => $oldRegistration->discount_amount,
                'tax_amount' => $request->tax_amount,
                'referred_member_by' => $oldRegistration->referred_member_by,
                'referred_commission' => $oldRegistration->referred_commission,
                'status' => 'Active',
            ]);

            // 3. CREATE ITEMS
            if ($oldRegistration->items->count() > 0) {
                foreach ($oldRegistration->items as $item) {
                    LockerRegistrationItem::create([
                        'registration_id' => $newRegistration->id,
                        'locker_id' => $item->locker_id,
                        'locker_number' => $item->locker_number,
                        'size' => $item->size,
                        'type' => $item->type,
                        'locker_group' => $item->locker_group,
                        'locker_position' => $item->locker_position,
                        'start_date' => $request->contract_start_date,
                        'end_date' => $request->contract_end_date,
                        'amount' => $item->amount,
                        'status' => 'active',
                        'added_at' => now(),
                    ]);
                }
            } elseif ($oldRegistration->locker) {
                LockerRegistrationItem::create([
                    'registration_id' => $newRegistration->id,
                    'locker_id' => $oldRegistration->locker->id,
                    'locker_number' => $oldRegistration->locker->locker_number,
                    'size' => $oldRegistration->locker->locker_size,
                    'type' => $oldRegistration->locker->locker_type,
                    'locker_group' => $oldRegistration->locker->locker_group ?? null,
                    'locker_position' => $oldRegistration->locker->locker_position ?? null,
                    'start_date' => $request->contract_start_date,
                    'end_date' => $request->contract_end_date,
                    'amount' => $oldRegistration->locker_amount ?? 0,
                    'status' => 'active',
                    'added_at' => now(),
                ]);
            }

            // 4. CREATE PAYMENT
            Payment::create([
                'registration_id' => $newRegistration->id,
                'payment_mode' => $paymentMethod,
                'total_amount' => $request->amount,
                'paid_amount' => $request->amount,
                'balance_amount' => 0,
                'payment_date' => $request->payment_date,
                'status' => 'paid',
                'transaction_id' => 'TXN' . time() . rand(1000, 9999),
                'notes' => $request->notes ?? null,
            ]);

            // ✅ 5. UPDATE OLD REGISTRATION LAST (IMPORTANT FIX)
            $oldRegistration->update(['status' => 'Expired']);

            foreach ($oldRegistration->items as $item) {
                $item->update(['status' => 'expired']);
            }

            DB::commit();

            return redirect()->route('customers.show', $client->id)
                ->with('success', 'Renewal completed successfully and payment saved.');
        } catch (\Exception $e) {
            DB::rollBack();

            \Log::error('Renewal processing failed', [
                'client_id' => $clientId,
                'registration_id' => $registrationId,
                'request' => $request->all(),
                'exception' => $e,
            ]);

            return redirect()->back()->with(
                'error',
                'Unable to process renewal: ' . ($e->getMessage() ?: 'Unexpected error')
            );
        }
    }
}
