<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\LockerPayment;
use App\Models\LockerRegistration;
use App\Models\MembershipPlan;
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,bank_transfer,online,cheque',
            '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);
        }
    }
}
