<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Models\BillPayment;
use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use App\Mail\BillPaymentSubmittedMail;
use App\Mail\BillPaymentStatusMail;
use App\Models\Deposit;

class BillsApiController extends Controller
{
    // Accept offer
    public function acceptOffer(Request $request, $id): JsonResponse
    {
        try {
            $user = auth()->user();
            $billPayment = BillPayment::where('id', $id)
                ->where('user_id', $user->id)
                ->first();

            if (!$billPayment) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Bill payment not found'
                ], 404);
            }

            // Check if offer is already accepted
            if ($billPayment->offer_status === BillPayment::STATUS_ACCEPTED) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This offer has already been accepted'
                ], 422);
            }

            // Check if offer is rejected
            if ($billPayment->offer_status === BillPayment::STATUS_REJECTED) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This offer has been rejected and cannot be accepted'
                ], 422);
            }
            
            if ($billPayment->final_amount > $user->ngn_balance) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error! Insufficient funds to cover Bill Payment. Please Topup First.'
                ], 422);
            }
            
            // Check if account is restricted
            if ($user->restricted == 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'Your account is restricted at the moment, kindly contact admin!'
                ], 422);
            }

            // $totalDeposits = Deposit::where('user_id', $user->id)->sum('amount');

            // if ($totalDeposits < 300) {
            //     return response()->json([
            //         'status' => 'error',
            //         'message' => 'Your account is yet to reach the minimum capital of $300, kindly continue to grow your account or deposit to reach the threshold!'
            //     ], 422);
            // }

            $totalDeposits = Deposit::where('user_id', $user->id)->sum('amount');
            
            if ($totalDeposits <= 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Your account has no deposits yet! Kindly make a deposit to proceed.'
                ], 422);
            }


            DB::beginTransaction();

            // Update offer status
            $billPayment->offer_status = BillPayment::STATUS_ACCEPTED;
            $billPayment->save();

            // Deduct the payment amount from the user's NGN balance and add cashback
            $user->ngn_balance -= $billPayment->final_amount;
            $user->ngn_balance += $billPayment->cashback_amount;
            $user->save();

            // Create notification for user
            $billType = match($billPayment->type) {
                BillPayment::TYPE_RENT => 'Rent',
                BillPayment::TYPE_SCHOOL_FEES => 'School Fees',
                BillPayment::TYPE_TRAVELS => 'Travel',
                default => 'Bill',
            };
            Notification::create([
                'user_id' => $user->id,
                'title' => "{$billType} Payment Accepted",
                'message' => "You have accepted the {$billType} payment offer. Amount: NGN " . number_format($billPayment->final_amount, 2) . ". Cashback: NGN " . number_format($billPayment->cashback_amount, 2) . ". Reference: {$billPayment->offer_id}",
                'status' => 0, // 0 = unread
            ]);

            DB::commit();

            // Send email notifications
            $this->sendOfferStatusEmail($billPayment, $user, 'pending', 'accepted');

            return response()->json([
                'status' => 'success',
                'message' => 'Offer accepted successfully.',
                'data' => [
                    'bill_payment' => $billPayment,
                    'new_balance' => $user->ngn_balance,
                ]
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Accept offer failed: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to accept offer',
                'error' => $e->getMessage()
            ], 500);
        }
    }


    public function rejectOffer(Request $request, $id): JsonResponse
    {
        try {
            $user = auth()->user();
            $billPayment = BillPayment::where('id', $id)
                ->where('user_id', $user->id)
                ->first();

            if (!$billPayment) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Bill payment not found'
                ], 404);
            }

            // Check if offer is already accepted
            if ($billPayment->offer_status === BillPayment::STATUS_ACCEPTED) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This offer has already been accepted and cannot be rejected'
                ], 422);
            }

            // Check if offer is already rejected
            if ($billPayment->offer_status === BillPayment::STATUS_REJECTED) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This offer has already been rejected'
                ], 422);
            }

            $billPayment->offer_status = BillPayment::STATUS_REJECTED;
            $billPayment->save();

            // Create notification for user
            $billType = match($billPayment->type) {
                BillPayment::TYPE_RENT => 'Rent',
                BillPayment::TYPE_SCHOOL_FEES => 'School Fees',
                BillPayment::TYPE_TRAVELS => 'Travel',
                default => 'Bill',
            };
            Notification::create([
                'user_id' => $user->id,
                'title' => "{$billType} Payment Rejected",
                'message' => "You have rejected the {$billType} payment offer. Reference: {$billPayment->offer_id}",
                'status' => 0, // 0 = unread
            ]);

            // Send email notifications
            $this->sendOfferStatusEmail($billPayment, $user, 'pending', 'rejected');

            return response()->json([
                'status' => 'success',
                'message' => 'Offer rejected successfully.'
            ]);
        } catch (\Exception $e) {
            Log::error('Reject offer failed: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to reject offer',
                'error' => $e->getMessage()
            ], 500);
        }
    }

  

    /**
     * Store a new rent payment request
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function storeRentPayment(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                // Snake case fields from frontend
                'bill_type' => 'required|string|in:rent',
                'tenant_name' => 'required|string|max:255',
                'landlord_name' => 'required|string|max:255',
                'property_address' => 'required|string|max:500',
                'original_amount' => 'required|numeric|min:0',
                'discount_percentage' => 'nullable|numeric|min:0|max:100',
                'discount_amount' => 'nullable|numeric|min:0',
                'cashback_percentage' => 'nullable|numeric|min:0|max:100',
                'cashback_amount' => 'nullable|numeric|min:0',
                'final_amount' => 'required|numeric|min:0',
                'payment_frequency' => 'nullable|string',
                'payment_method' => 'nullable|string',
                'due_date' => 'required|date',
                'consistency' => 'nullable|string',
                'offer_status' => 'nullable|string',
                
                // Bank payment fields
                'account_name' => 'nullable|string|max:255',
                'account_number' => 'nullable|string|max:100',
                'bank_name' => 'nullable|string|max:255',
                
                // Card payment fields
                'card_holder_name' => 'nullable|string|max:255',
                'card_payment_link' => 'nullable|string|max:500',
                
                // Cash payment fields
                'cash_location' => 'nullable|string|max:500',
                'cash_recipient_name' => 'nullable|string|max:255',
                
                // Mobile money payment fields
                'mobile_number' => 'nullable|string|max:50',
                'mobile_provider' => 'nullable|string|max:100',
            ]);

            $user = auth()->user();

            // Check if account is restricted
            if ($user->restricted == 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'Your account is restricted at the moment, kindly contact admin!'
                ], 422);
            }
            
            // $totalDeposits = totalDeposits($user);
            
            // if (!$totalDeposits) {
            //     return response()->json([
            //         'status' => 'error',
            //         'message' => 'Your account is yet to reach the minimum capital of $300, kindly continue to grow your account or deposit to reach the threshold!'
            //     ], 422);
            // }

            $totalDeposits = Deposit::where('user_id', $user->id)->sum('amount');
            
            if ($totalDeposits <= 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Your account has no deposits yet! Kindly make a deposit to proceed.'
                ], 422);
            }

            // Generate unique offer ID
            $offerId = 'RENT-' . time() . rand(1000, 9999);

            DB::beginTransaction();

            $billPayment = BillPayment::create([
                'user_id' => $user->id,
                'type' => BillPayment::TYPE_RENT,
                'offer_id' => $offerId,
                'payer_name' => $validated['tenant_name'],
                'recipient_name' => $validated['landlord_name'],
                'description' => "Rent payment for {$validated['property_address']}",
                'property_address' => $validated['property_address'],
                'amount' => $validated['original_amount'],
                'original_amount' => $validated['original_amount'],
                'discount_percentage' => $validated['discount_percentage'] ?? 0,
                'discount_amount' => $validated['discount_amount'] ?? 0,
                'cashback_percentage' => $validated['cashback_percentage'] ?? 0,
                'cashback_amount' => $validated['cashback_amount'] ?? 0,
                'final_amount' => $validated['final_amount'],
                'payment_frequency' => $validated['payment_frequency'] ?? 'monthly',
                'payment_method' => $validated['payment_method'] ?? 'cash',
                'due_date' => $validated['due_date'],
                'consistency' => $validated['consistency'] ?? null,
                'offer_status' => $validated['offer_status'] ?? 'pending',
                'status' => BillPayment::STATUS_PENDING,
                'submitted_at' => now(),
                'offer_expires_at' => now()->addHours(24),
                
                // Bank payment fields
                'account_name' => $validated['account_name'] ?? null,
                'account_number' => $validated['account_number'] ?? null,
                'bank_name' => $validated['bank_name'] ?? null,
                
                // Card payment fields
                'card_holder_name' => $validated['card_holder_name'] ?? null,
                'card_payment_link' => $validated['card_payment_link'] ?? null,
                
                // Cash payment fields
                'cash_location' => $validated['cash_location'] ?? null,
                'cash_recipient_name' => $validated['cash_recipient_name'] ?? null,
                
                // Mobile money payment fields
                'mobile_number' => $validated['mobile_number'] ?? null,
                'mobile_provider' => $validated['mobile_provider'] ?? null,
            ]);

            // Create notification for user
            Notification::create([
                'user_id' => $user->id,
                'title' => 'Rent Payment Submitted',
                'message' => "Your rent payment request for {$validated['property_address']} has been submitted successfully. Reference: {$offerId}",
                'status' => 0, // 0 = unread, 1 = read
            ]);

            DB::commit();

            // Send email notifications
            $this->sendBillSubmissionEmails($billPayment, $user);

            return response()->json([
                'status' => 'success',
                'message' => 'Rent payment request submitted successfully',
                'data' => [
                    'bill_payment' => $billPayment,
                ]
            ], 201);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Rent payment creation failed: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to submit rent payment request',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a new school fees payment request
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function storeSchoolFees(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                // Snake case fields from frontend
                'bill_type' => 'required|string|in:school_fees',
                'student_name' => 'required|string|max:255',
                'school_name' => 'required|string|max:255',
                'admission_no' => 'required|string|max:100',
                'fee_type' => 'nullable|string',
                'semester' => 'nullable|string',
                'original_amount' => 'required|numeric|min:0',
                'discount_percentage' => 'nullable|numeric|min:0|max:100',
                'discount_amount' => 'nullable|numeric|min:0',
                'cashback_percentage' => 'nullable|numeric|min:0|max:100',
                'cashback_amount' => 'nullable|numeric|min:0',
                'final_amount' => 'required|numeric|min:0',
                'due_date' => 'required|date',
                'payment_history' => 'nullable|string',
                'payment_method' => 'nullable|string',
                'offer_status' => 'nullable|string',
                
                // Bank payment fields
                'account_name' => 'nullable|string|max:255',
                'account_number' => 'nullable|string|max:100',
                'bank_name' => 'nullable|string|max:255',
                
                // Card payment fields
                'card_holder_name' => 'nullable|string|max:255',
                'card_payment_link' => 'nullable|string|max:500',
                
                // Cash payment fields
                'cash_location' => 'nullable|string|max:500',
                'cash_recipient_name' => 'nullable|string|max:255',
                
                // Mobile money payment fields
                'mobile_number' => 'nullable|string|max:50',
                'mobile_provider' => 'nullable|string|max:100',
            ]);

            $user = auth()->user();

            // Check if account is restricted
            if ($user->restricted == 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'Your account is restricted at the moment, kindly contact admin!'
                ], 422);
            }
            
            // $totalDeposits = totalDeposits($user);
            
            // if (!$totalDeposits) {
            //     return response()->json([
            //         'status' => 'error',
            //         'message' => 'Your account is yet to reach the minimum capital of $300, kindly continue to grow your account or deposit to reach the threshold!'
            //     ], 422);
            // }

            $totalDeposits = Deposit::where('user_id', $user->id)->sum('amount');
            
            if ($totalDeposits <= 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Your account has no deposits yet! Kindly make a deposit to proceed.'
                ], 422);
            }

            // Generate unique offer ID
            $offerId = 'SCHOOL-' . time() . rand(1000, 9999);

            DB::beginTransaction();

            $billPayment = BillPayment::create([
                'user_id' => $user->id,
                'type' => BillPayment::TYPE_SCHOOL_FEES,
                'offer_id' => $offerId,
                'payer_name' => $validated['student_name'],
                'recipient_name' => $validated['school_name'],
                'description' => "School fees for {$validated['student_name']} at {$validated['school_name']}",
                'school_name' => $validated['school_name'],
                'admission_no' => $validated['admission_no'],
                'fee_type' => $validated['fee_type'] ?? 'tuition',
                'semester' => $validated['semester'] ?? null,
                'amount' => $validated['original_amount'],
                'original_amount' => $validated['original_amount'],
                'discount_percentage' => $validated['discount_percentage'] ?? 0,
                'discount_amount' => $validated['discount_amount'] ?? 0,
                'cashback_percentage' => $validated['cashback_percentage'] ?? 0,
                'cashback_amount' => $validated['cashback_amount'] ?? 0,
                'final_amount' => $validated['final_amount'],
                'due_date' => $validated['due_date'],
                'payment_method' => $validated['payment_method'] ?? 'cash',
                'payment_history' => $validated['payment_history'] ?? null,
                'offer_status' => $validated['offer_status'] ?? 'pending',
                'status' => BillPayment::STATUS_PENDING,
                'submitted_at' => now(),
                'offer_expires_at' => now()->addHours(24),
                
                // Bank payment fields
                'account_name' => $validated['account_name'] ?? null,
                'account_number' => $validated['account_number'] ?? null,
                'bank_name' => $validated['bank_name'] ?? null,
                
                // Card payment fields
                'card_holder_name' => $validated['card_holder_name'] ?? null,
                'card_payment_link' => $validated['card_payment_link'] ?? null,
                
                // Cash payment fields
                'cash_location' => $validated['cash_location'] ?? null,
                'cash_recipient_name' => $validated['cash_recipient_name'] ?? null,
                
                // Mobile money payment fields
                'mobile_number' => $validated['mobile_number'] ?? null,
                'mobile_provider' => $validated['mobile_provider'] ?? null,
            ]);

            // Create notification for user
            Notification::create([
                'user_id' => $user->id,
                'title' => 'School Fees Payment Submitted',
                'message' => "Your school fees payment request for {$validated['student_name']} at {$validated['school_name']} has been submitted successfully. Reference: {$offerId}",
                'status' => 0, // 0 = unread, 1 = read
            ]);

            DB::commit();

            // Send email notifications
            $this->sendBillSubmissionEmails($billPayment, $user);

            return response()->json([
                'status' => 'success',
                'message' => 'School fees payment request submitted successfully',
                'data' => [
                    'bill_payment' => $billPayment,
                ]
            ], 201);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('School fees creation failed: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to submit school fees payment request',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a new travel payment request
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function storeTravels(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                // Snake case fields from frontend
                'bill_type' => 'required|string|in:travels',
                'traveler_name' => 'required|string|max:255',
                'travel_type' => 'required|string|max:100', // flight_local, flight_international, bus, train, etc.
                'travel_type_name' => 'nullable|string|max:255',
                'provider_name' => 'required|string|max:255', // Emirates, Kenya Airways, etc.
                'destination' => 'required|string|max:255',
                'travel_date' => 'required|date',
                'contact_phone' => 'nullable|string|max:50',
                'additional_details' => 'nullable|string',
                'original_amount' => 'required|numeric|min:0',
                'discount_percentage' => 'nullable|numeric|min:0|max:100',
                'discount_amount' => 'nullable|numeric|min:0',
                'cashback_percentage' => 'nullable|numeric|min:0|max:100',
                'cashback_amount' => 'nullable|numeric|min:0',
                'final_amount' => 'required|numeric|min:0',
                'payment_history' => 'nullable|string',
                'payment_method' => 'nullable|string',
                'offer_status' => 'nullable|string',
                
                // Bank payment fields
                'account_name' => 'nullable|string|max:255',
                'account_number' => 'nullable|string|max:100',
                'bank_name' => 'nullable|string|max:255',
                
                // Card payment fields
                'card_holder_name' => 'nullable|string|max:255',
                'card_payment_link' => 'nullable|string|max:500',
                
                // Cash payment fields
                'cash_location' => 'nullable|string|max:500',
                'cash_recipient_name' => 'nullable|string|max:255',
                
                // Mobile money payment fields
                'mobile_number' => 'nullable|string|max:50',
                'mobile_provider' => 'nullable|string|max:100',
            ]);

            $user = auth()->user();

            // Check if account is restricted
            if ($user->restricted == 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'Your account is restricted at the moment, kindly contact admin!'
                ], 422);
            }
            
            // $totalDeposits = totalDeposits($user);
            
            // if (!$totalDeposits) {
            //     return response()->json([
            //         'status' => 'error',
            //         'message' => 'Your account is yet to reach the minimum capital of $300, kindly continue to grow your account or deposit to reach the threshold!'
            //     ], 422);
            // }

            $totalDeposits = Deposit::where('user_id', $user->id)->sum('amount');
            
            if ($totalDeposits <= 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Your account has no deposits yet! Kindly make a deposit to proceed.'
                ], 422);
            }

            // Generate unique offer ID
            $offerId = 'TRV-' . time() . rand(1000, 9999);

            DB::beginTransaction();

            $billPayment = BillPayment::create([
                'user_id' => $user->id,
                'type' => BillPayment::TYPE_TRAVELS,
                'offer_id' => $validated['offer_id'] ?? $offerId,
                'payer_name' => $validated['traveler_name'],
                'recipient_name' => $validated['provider_name'],
                'description' => $validated['description'] ?? "{$validated['travel_type_name']} - {$validated['destination']}",
                
                // Travel-specific fields
                'traveler_name' => $validated['traveler_name'],
                'travel_type' => $validated['travel_type'],
                'travel_type_name' => $validated['travel_type_name'] ?? null,
                'provider_name' => $validated['provider_name'],
                'destination' => $validated['destination'],
                'travel_date' => $validated['travel_date'],
                'contact_phone' => $validated['contact_phone'] ?? null,
                'additional_details' => $validated['additional_details'] ?? null,
                
                // Amount fields
                'amount' => $validated['original_amount'],
                'original_amount' => $validated['original_amount'],
                'discount_percentage' => $validated['discount_percentage'] ?? 0,
                'discount_amount' => $validated['discount_amount'] ?? 0,
                'cashback_percentage' => $validated['cashback_percentage'] ?? 0,
                'cashback_amount' => $validated['cashback_amount'] ?? 0,
                'final_amount' => $validated['final_amount'],
                'due_date' => $validated['travel_date'],
                'payment_method' => $validated['payment_method'] ?? 'cash',
                'payment_history' => $validated['payment_history'] ?? null,
                'offer_status' => $validated['offer_status'] ?? 'pending',
                'status' => BillPayment::STATUS_PENDING,
                'submitted_at' => now(),
                'offer_expires_at' => now()->addHours(24),
                
                // Bank payment fields
                'account_name' => $validated['account_name'] ?? null,
                'account_number' => $validated['account_number'] ?? null,
                'bank_name' => $validated['bank_name'] ?? null,
                
                // Card payment fields
                'card_holder_name' => $validated['card_holder_name'] ?? null,
                'card_payment_link' => $validated['card_payment_link'] ?? null,
                
                // Cash payment fields
                'cash_location' => $validated['cash_location'] ?? null,
                'cash_recipient_name' => $validated['cash_recipient_name'] ?? null,
                
                // Mobile money payment fields
                'mobile_number' => $validated['mobile_number'] ?? null,
                'mobile_provider' => $validated['mobile_provider'] ?? null,
            ]);

            // Create notification for user
            Notification::create([
                'user_id' => $user->id,
                'title' => 'Travel Payment Submitted',
                'message' => "Your travel payment request for {$validated['destination']} via {$validated['provider_name']} has been submitted successfully. Reference: {$billPayment->offer_id}",
                'status' => 0, // 0 = unread, 1 = read
            ]);

            DB::commit();

            // Send email notifications
            $this->sendBillSubmissionEmails($billPayment, $user);

            return response()->json([
                'status' => 'success',
                'message' => 'Travel payment request submitted successfully',
                'data' => [
                    'bill_payment' => $billPayment,
                ]
            ], 201);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Travel payment creation failed: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to submit travel payment request',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's bill payments
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $user = auth()->user();
            $query = BillPayment::where('user_id', $user->id);

            // Filter by type
            if ($request->has('type') && !empty($request->type)) {
                $query->where('type', $request->type);
            }

            // Filter by status
            if ($request->has('status') && !empty($request->status)) {
                $query->where('status', $request->status);
            }

            // Filter by date range
            if ($request->has('from_date') && !empty($request->from_date)) {
                $query->whereDate('created_at', '>=', $request->from_date);
            }

            if ($request->has('to_date') && !empty($request->to_date)) {
                $query->whereDate('created_at', '<=', $request->to_date);
            }

            $billPayments = $query->orderBy('created_at', 'DESC')->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'bill_payments' => $billPayments,
                    'summary' => [
                        'total' => BillPayment::where('user_id', $user->id)->count(),
                        'pending' => BillPayment::where('user_id', $user->id)->pending()->count(),
                        'accepted' => BillPayment::where('user_id', $user->id)->accepted()->count(),
                        'approved' => BillPayment::where('user_id', $user->id)->approved()->count(),
                        'rejected' => BillPayment::where('user_id', $user->id)->rejected()->count(),
                        'by_type' => [
                            'rent' => BillPayment::where('user_id', $user->id)->rent()->count(),
                            'school_fees' => BillPayment::where('user_id', $user->id)->schoolFees()->count(),
                            'travels' => BillPayment::where('user_id', $user->id)->travels()->count(),
                        ]
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch bill payments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's pending bill payments (offer_status = pending)
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function getPendingOffers(Request $request): JsonResponse
    {
        try {
            $user = auth()->user();
            $query = BillPayment::where('user_id', $user->id)
                ->where('offer_status', 'pending');

            // Filter by type
            if ($request->has('type') && !empty($request->type)) {
                $query->where('type', $request->type);
            }

            $billPayments = $query->orderBy('created_at', 'DESC')->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'bill_payments' => $billPayments,
                    'summary' => [
                        'total' => $billPayments->count(),
                        'rent' => $billPayments->where('type', BillPayment::TYPE_RENT)->count(),
                        'school_fees' => $billPayments->where('type', BillPayment::TYPE_SCHOOL_FEES)->count(),
                        'travels' => $billPayments->where('type', BillPayment::TYPE_TRAVELS)->count(),
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch pending offers',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's rent payments
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function getRentPayments(Request $request): JsonResponse
    {
        try {
            $user = auth()->user();
            $query = BillPayment::where('user_id', $user->id)->rent();

            // Filter by status
            if ($request->has('status') && !empty($request->status)) {
                $query->where('status', $request->status);
            }

            // Filter by date range
            if ($request->has('from_date') && !empty($request->from_date)) {
                $query->whereDate('created_at', '>=', $request->from_date);
            }

            if ($request->has('to_date') && !empty($request->to_date)) {
                $query->whereDate('created_at', '<=', $request->to_date);
            }

            $billPayments = $query->orderBy('created_at', 'DESC')->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'bill_payments' => $billPayments,
                    'summary' => [
                        'total' => BillPayment::where('user_id', $user->id)->rent()->count(),
                        'pending' => BillPayment::where('user_id', $user->id)->rent()->pending()->count(),
                        'accepted' => BillPayment::where('user_id', $user->id)->rent()->accepted()->count(),
                        'approved' => BillPayment::where('user_id', $user->id)->rent()->approved()->count(),
                        'rejected' => BillPayment::where('user_id', $user->id)->rent()->rejected()->count(),
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch rent payments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's school fees payments
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function getSchoolFees(Request $request): JsonResponse
    {
        try {
            $user = auth()->user();
            $query = BillPayment::where('user_id', $user->id)->schoolFees();

            // Filter by status
            if ($request->has('status') && !empty($request->status)) {
                $query->where('status', $request->status);
            }

            // Filter by date range
            if ($request->has('from_date') && !empty($request->from_date)) {
                $query->whereDate('created_at', '>=', $request->from_date);
            }

            if ($request->has('to_date') && !empty($request->to_date)) {
                $query->whereDate('created_at', '<=', $request->to_date);
            }

            $billPayments = $query->orderBy('created_at', 'DESC')->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'bill_payments' => $billPayments,
                    'summary' => [
                        'total' => BillPayment::where('user_id', $user->id)->schoolFees()->count(),
                        'pending' => BillPayment::where('user_id', $user->id)->schoolFees()->pending()->count(),
                        'accepted' => BillPayment::where('user_id', $user->id)->schoolFees()->accepted()->count(),
                        'approved' => BillPayment::where('user_id', $user->id)->schoolFees()->approved()->count(),
                        'rejected' => BillPayment::where('user_id', $user->id)->schoolFees()->rejected()->count(),
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch school fees payments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's travel payments
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function getTravels(Request $request): JsonResponse
    {
        try {
            $user = auth()->user();
            $query = BillPayment::where('user_id', $user->id)->travels();

            // Filter by status
            if ($request->has('status') && !empty($request->status)) {
                $query->where('status', $request->status);
            }

            // Filter by date range
            if ($request->has('from_date') && !empty($request->from_date)) {
                $query->whereDate('created_at', '>=', $request->from_date);
            }

            if ($request->has('to_date') && !empty($request->to_date)) {
                $query->whereDate('created_at', '<=', $request->to_date);
            }

            $billPayments = $query->orderBy('created_at', 'DESC')->get();

            return response()->json([
                'status' => 'success',
                'data' => [
                    'bill_payments' => $billPayments,
                    'summary' => [
                        'total' => BillPayment::where('user_id', $user->id)->travels()->count(),
                        'pending' => BillPayment::where('user_id', $user->id)->travels()->pending()->count(),
                        'accepted' => BillPayment::where('user_id', $user->id)->travels()->accepted()->count(),
                        'approved' => BillPayment::where('user_id', $user->id)->travels()->approved()->count(),
                        'rejected' => BillPayment::where('user_id', $user->id)->travels()->rejected()->count(),
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch travel payments',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get a single bill payment by ID
     * 
     * @param int $id
     * @return JsonResponse
     */
    public function show($id): JsonResponse
    {
        try {
            $user = auth()->user();
            $billPayment = BillPayment::where('user_id', $user->id)
                ->where('id', $id)
                ->first();

            if (!$billPayment) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Bill payment not found'
                ], 404);
            }

            return response()->json([
                'status' => 'success',
                'data' => [
                    'bill_payment' => $billPayment,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch bill payment',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Send email notifications for bill submission
     * 
     * @param BillPayment $billPayment
     * @param \App\Models\User $user
     * @return void
     */
    protected function sendBillSubmissionEmails(BillPayment $billPayment, $user): void
    {
        try {
            if (!env('DEMO_MODE')) {
                // Send to user
                Mail::to($user->email)->send(new BillPaymentSubmittedMail($billPayment, $user));

                // Send to admin
                $adminEmail = site('email') ?? config('mail.admin_email');
                if ($adminEmail) {
                    Mail::to($adminEmail)->send(new BillPaymentSubmittedMail($billPayment, $user, true));
                }
            }
        } catch (\Exception $e) {
            Log::error("Failed to send bill submission email: " . $e->getMessage());
        }
    }

    /**
     * Send email notifications for offer status change (accept/reject)
     * 
     * @param BillPayment $billPayment
     * @param \App\Models\User $user
     * @param string $oldStatus
     * @param string $newStatus
     * @return void
     */
    protected function sendOfferStatusEmail(BillPayment $billPayment, $user, string $oldStatus, string $newStatus): void
    {
        try {
            if (!env('DEMO_MODE')) {
                // Send to user
                Mail::to($user->email)->send(new BillPaymentStatusMail($billPayment, $oldStatus, $newStatus));

                // Send to admin
                $adminEmail = site('email') ?? config('mail.admin_email');
                if ($adminEmail) {
                    Mail::to($adminEmail)->send(new BillPaymentStatusMail($billPayment, $oldStatus, $newStatus));
                }
            }
        } catch (\Exception $e) {
            Log::error("Failed to send offer status email: " . $e->getMessage());
        }
    }
}
