<?php

namespace App\Http\Controllers;

use App\Mail\PaymentSuccessMail;
use App\Models\Category;
use App\Models\MeetingSchedule;
use Illuminate\Http\Request;
use App\Models\Member;
use App\Models\Month;
use App\Models\Payment;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;

class MemberController extends Controller
{
    // public function index(Request $request)
    // {
    //     $title = 'Member Master';
    //     $search = $request->input('search');

    //     $members = Member::with('category')
    //         ->when($search, function ($query, $search) {
    //             return $query->where('name', 'like', "%{$search}%")
    //                         ->orWhere('email', 'like', "%{$search}%")
    //                         ->orWhere('company', 'like', "%{$search}%")
    //                         ->orWhere('phone', 'like', "%{$search}%")
    //                         ->orWhereHas('category', function ($query) use ($search) {
    //                             $query->where('name', 'like', "%{$search}%");
    //                         });
    //         })
    //         ->paginate(10);

    //     return view('members.index', compact('title', 'members', 'search'));
    // }

    public function index(Request $request)
    {
        $title = 'Member Master';
        $search = $request->input('search');

        $members = Member::with([
            'category:id,name',
            'expireSchedule:id,name,year',
            'renewalSchedule:id,name,year'
        ])
            ->select('id', 'category_id', 'name', 'company', 'phone', 'email', 'expire_month_id', 'renewal_month_id')
            ->when($search, function ($query, $search) {
                return $query->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('company', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhereHas('category', function ($query) use ($search) {
                        $query->where('name', 'like', "%{$search}%");
                    });
            })
            ->orderBy('id', 'desc')
            ->paginate(10);

        $categories = Category::where('is_active', '1')->get();

        $upcomingMeeting = MeetingSchedule::where('status', 'scheduled')->limit(1)->first();

        return view('members.index', compact('title', 'members', 'search', 'categories', 'upcomingMeeting'));
    }

    // public function store(Request $request)
    // {
    //     // First add this category. then get id.
    //     $request->validate([
    //         'name' => 'required|string|max:255',
    //         'company' => 'required|string|max:255',
    //         'phone' => 'required|string|max:20',
    //         'email' => 'required|email|max:255',
    //         'category' => 'required|exists:categories,id',
    //     ]);

    //     Member::create([
    //         'name' => $request->name,
    //         'company' => $request->company,
    //         'phone' => $request->phone,
    //         'email' => $request->email,
    //         'category_id' => $request->category,
    //     ]);

    //     return redirect()->route('members')->with('success', 'Member created successfully');
    // }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'company' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'required|email|max:255',
            'category' => 'required|string|max:255',
        ]);

        $category = Category::firstOrCreate(['name' => $request->category]);

        Member::create([
            'name' => $request->name,
            'company' => $request->company,
            'phone' => $request->phone,
            'email' => $request->email,
            'category_id' => $category->id,
        ]);

        return redirect()->route('members')->with('success', 'Member created successfully');
    }

    // public function payment($memberId)
    // {
    //     $title = 'Member Payment';
    //     $member = Member::with(['category:id,name', 'expireSchedule:id,name,year', 'renewalSchedule:id,name,year'])
    //         ->find($memberId);

    //     $upcomingMonth = MeetingSchedule::where('status', 'scheduled')->limit(1)->first();

    //     // Get current month ID from months table using Month model
    //     $currentMonth = Month::getCurrentMonth();

    //     // Late Fee Calculation

    //     if (!$member) {
    //         return redirect()->route('members')->with('error', 'Member not found');
    //     }

    //     return view('members.payment', compact('title', 'member', 'upcomingMonth', 'currentMonth'));
    // }

    // public function payment($memberId)
    // {
    //     $title = 'Member Payment';

    //     $member = Member::with([
    //         'category:id,name',
    //         'expireSchedule:id,name,year',
    //         'renewalSchedule:id,name,year'
    //     ])->find($memberId);

    //     if (!$member) {
    //         return redirect()->route('members')->with('error', 'Member not found');
    //     }

    //     $upcomingMonth = MeetingSchedule::where('status', 'scheduled')->first();

    //     // Current month from helper
    //     $currentMonth = Month::getCurrentMonth();

    //     // 🔥 Late Fee Calculation
    //     $lateFee = 0;

    //     if ($member->renewalSchedule) {
    //         // Get due date (assume 1st of that month)
    //         $dueDate = Carbon::create(
    //             $member->renewalSchedule->year,
    //             $member->renewalSchedule->id, // month id (1-12)
    //             1
    //         );

    //         $today = Carbon::today();

    //         // Add 15 days grace
    //         $graceDate = $dueDate->copy()->addDays(15);

    //         if ($today->greaterThan($graceDate)) {

    //             // Months difference after grace
    //             $monthsLate = $graceDate->diffInMonths($today);

    //             // Get late fee from months table (current or due month)
    //             $monthlyLateFee = Month::find($member->renewalSchedule->id)->late_fee ?? 0;

    //             $penalty = ($monthsLate + 1) * $monthlyLateFee;
    //         }
    //     }

    //     return view('members.payment', compact(
    //         'title',
    //         'member',
    //         'upcomingMonth',
    //         'currentMonth',
    //         'penalty'
    //     ));
    // }

    public function payment($memberId)
    {
        $title = 'Member Payment';

        $member = Member::with([
            'category:id,name',
            'expireSchedule:id,name,year',
            'renewalSchedule:id,name,year'
        ])->find($memberId);

        if (!$member) {
            return redirect()->route('members')->with('error', 'Member not found');
        }

        $upcomingMonth = MeetingSchedule::where('status', 'scheduled')->first();
        $currentMonth = Month::getCurrentMonth();

        $penalty = 0;
        $lateFeeMonths = [];

        if ($member->renewalSchedule) {
            $dueMonthName = $member->renewalSchedule->name;
            $dueYear = $member->renewalSchedule->year;

            $monthNumber = Carbon::parse("1 {$dueMonthName} {$dueYear}")->month;

            $dueDate = Carbon::create($dueYear, $monthNumber, 1);
            $graceEndDate = $dueDate->copy()->addDays(15);
            $today = Carbon::today();

            if ($today->greaterThan($graceEndDate)) {
                $startDate = $dueDate->copy()->startOfMonth();
                $endDate = $today->copy()->startOfMonth();

                while ($startDate->lte($endDate)) {
                    $monthRow = Month::where('name', $startDate->format('F'))
                        ->where('year', $startDate->year)
                        ->first();

                    if ($monthRow) {
                        $penalty += (float) $monthRow->late_fee;

                        $lateFeeMonths[] = [
                            'name' => $monthRow->name,
                            'year' => $monthRow->year,
                            'late_fee' => $monthRow->late_fee,
                        ];
                    }

                    $startDate->addMonth();
                }
            }
        }

        return view('members.payment', compact(
            'title',
            'member',
            'upcomingMonth',
            'currentMonth',
            'penalty',
            'lateFeeMonths'
        ));
    }

    public function calculateEndMonth(Request $request)
    {
        $duration = $request->get('duration');
        $paymentFrom = $request->get('payment_from');

        if (!$duration) {
            return response()->json(['error' => 'Duration is required'], 400);
        }

        // Cast duration to integer
        $duration = (int) $duration;

        // Simple calculation logic using month IDs
        if ($paymentFrom) {
            // payment_from is the month_id from months table
            $paymentFromMonthId = (int) $paymentFrom;
            $paymentToMonthId = $paymentFromMonthId + ($duration - 1);
            $renewalMonthId = $paymentToMonthId + 1;

            // Get month details for payment_to
            $paymentToMonth = \App\Models\Month::find($paymentToMonthId);
            $renewalMonth = \App\Models\Month::find($renewalMonthId);

            // Get meeting schedule for payment_to month
            $lastMeeting = null;
            if ($paymentToMonth) {
                $lastMeeting = \App\Models\MeetingSchedule::whereYear('meeting_date', $paymentToMonth->year)
                    ->whereMonth('meeting_date', date('m', strtotime($paymentToMonth->name . ' 1')))
                    ->orderBy('meeting_date', 'desc')
                    ->first();
            }

            return response()->json([
                'payment_to_month_id' => $paymentToMonthId,
                'payment_to_month_name' => $paymentToMonth ? $paymentToMonth->name : null,
                'payment_to_month_year' => $paymentToMonth ? $paymentToMonth->year : null,
                'payment_to_display' => $paymentToMonth ? $paymentToMonth->name . ' ' . $paymentToMonth->year : null,
                'renewal_month_id' => $renewalMonthId,
                'renewal_month_name' => $renewalMonth ? $renewalMonth->name : null,
                'renewal_month_year' => $renewalMonth ? $renewalMonth->year : null,
                'renewal_display' => $renewalMonth ? $renewalMonth->name . ' ' . $renewalMonth->year : null,
                'last_meeting_record' => $lastMeeting
            ]);
        }
    }

    // public function paymentStore(Request $request)
    // {
    //     // Validate the request
    //     $request->validate([
    //         'member_id' => 'required|exists:members,id',
    //         'payment_duration' => 'required|integer|min:1',
    //         'payment_from' => 'nullable|exists:meeting_schedules,id',
    //         'payment_end_month' => 'required',
    //         'amount' => 'required',
    //         'penalty' => 'required',
    //         'payment_method' => 'required',
    //         'upi_number' => 'required_if:payment_method,upi|string|max:255',
    //         'upi_transaction_id' => 'required_if:payment_method,upi|string|max:255',
    //     ]);

    //     // Get the member
    //     $member = Member::find($request->member_id);

    //     if (!$member) {
    //         return redirect()->route('members')->with('error', 'Member not found');
    //     }

    //     // Calculate end month
    //     $duration = $request->payment_duration;
    //     $paymentFrom = $request->payment_from;

    //     if ($paymentFrom) {
    //         $meetingSchedule = \App\Models\MeetingSchedule::find($paymentFrom);
    //         if ($meetingSchedule) {
    //             $currentDate = \Carbon\Carbon::create(
    //                 $meetingSchedule->year,
    //                 $meetingSchedule->month,
    //                 1
    //             );
    //         } else {
    //             $currentDate = now();
    //         }
    //     } else {
    //         $currentDate = now();
    //     }

    //     $endDate = $currentDate->copy()->addMonths($duration - 1);
    //     $endMonth = $endDate->format('F Y');

    //     // Create payment record
    //     $payment = new \App\Models\Payment();
    //     $payment->member_id = $member->id;
    //     $payment->duration = $duration;
    //     $payment->payment_from = $paymentFrom;
    //     $payment->payment_end_month = $request->payment_end_month; // Use the meeting schedule ID from form
    //     $payment->amount = $this->cleanAmount($request->amount); // Clean amount before storing
    //     $payment->penalty = $this->cleanAmount($request->penalty); // Clean penalty before storing
    //     $payment->payment_date = now();
    //     $payment->payment_method = $request->payment_method;

    //     // Add UPI details if payment method is UPI
    //     if ($request->payment_method === 'upi') {
    //         $payment->upi_number = $request->upi_number;
    //         $payment->transaction_number = $request->upi_transaction_id;
    //     }

    //     $payment->save();

    //     // Update to members table
    //     $member->update([
    //         'expire_schedule_id' => $request->payment_end_month,
    //         'renewal_schedule_id' => $request->payment_end_month + 1,
    //     ]);

    //     return redirect()->route('members')->with('success', 'Payment recorded successfully');
    // }

    public function paymentStore(Request $request)
    {
        // Validation
        $request->validate([
            'member_id' => 'required|exists:members,id',
            'payment_duration' => 'required|integer|min:1',
            'payment_from' => 'nullable|exists:meeting_schedules,id',
            'payment_end_month' => 'required',
            'amount' => 'required',
            'payment_method' => 'required',
            'upi_number' => 'required_if:payment_method,upi',
            // 'upi_transaction_id' => 'required_if:payment_method,upi',
            'upi_transaction_id' => 'nullable',
        ]);

        // Get Member
        $member = Member::find($request->member_id);

        if (!$member) {
            return redirect()->route('members')->with('error', 'Member not found');
        }

        // Get renewal date (IMPORTANT)
        $renewalSchedule = \App\Models\Month::find($member->renewal_month_id);

        $penalty = 0;
        $lateFeeMonths = [];

        if ($renewalSchedule) {
            $dueMonthName = $renewalSchedule->name;
            $dueYear = $renewalSchedule->year;

            $monthNumber = Carbon::parse("1 {$dueMonthName} {$dueYear}")->month;

            $dueDate = Carbon::create($dueYear, $monthNumber, 1);
            $graceEndDate = $dueDate->copy()->addDays(15);
            $today = Carbon::today();

            if ($today->greaterThan($graceEndDate)) {
                $startDate = $dueDate->copy()->startOfMonth();
                $endDate = $today->copy()->startOfMonth();

                while ($startDate->lte($endDate)) {
                    $monthRow = \App\Models\Month::where('name', $startDate->format('F'))
                        ->where('year', $startDate->year)
                        ->first();

                    if ($monthRow) {
                        $penalty += (float) $monthRow->late_fee;

                        $lateFeeMonths[] = [
                            'name' => $monthRow->name,
                            'year' => $monthRow->year,
                            'late_fee' => $monthRow->late_fee,
                        ];
                    }

                    $startDate->addMonth();
                }
            }
        }

        // Clean amount
        $amount = $this->cleanAmount($request->amount);

        // Create Payment
        $payment = new Payment();
        $payment->member_id = $member->id;
        $payment->duration = $request->payment_duration;
        $payment->payment_from = $request->payment_from;
        $payment->payment_end_month = $request->payment_end_month;
        $payment->amount = $amount;
        $payment->penalty = $penalty; // backend calculated
        $payment->payment_date = now();
        $payment->payment_method = $request->payment_method;

        // UPI
        if ($request->payment_method === 'upi') {
            $payment->upi_number = $request->upi_number;
            $payment->transaction_number = $request->upi_transaction_id;
        }

        $payment->save();

        // Update Member
        $member->update([
            'expire_month_id' => $request->payment_end_month,
            'renewal_month_id' => $request->payment_end_month + 1,
        ]);
        // $paymentDateFormatted = now()->format('jS F Y'); // 23rd April 2026
        $paymentDateFormatted = now()->format('F Y'); // April 2026
        // Month Year

        if ($payment->duration == 1) {
            $paidMonthData = Month::find($request->payment_end_month);
            $paidMonth = $paidMonthData->month_name . ' ' . $paidMonthData->year;
            $subject = "Acknowledgement of Monthly Payment for the month of {$paymentDateFormatted}.";
            $paidContent = "We would like to acknowledge receipt of your monthly payment, made at Pullman Hotels on {$paymentDateFormatted} via {$request->payment_method}.";
        } elseif ($payment->duration == 3 || $payment->duration == 6) {
            $paidMonthFrom = Month::find($request->payment_end_month);
            $paidMonthTo = Month::find($request->payment_end_month + 2);
            $paidMonth = $paidMonthFrom->name . ' ' . $paidMonthFrom->year . ' to ' . $paidMonthTo->name . ' ' . $paidMonthTo->year;
            $subject = "Smart Savings & Strong Commitment - BNI Brios!!";
            $paidContent = "We would like to sincerely appreciate your proactive step in making a lump sum payment of ₹{$payment->amount}, covering your next {$payment->duration} months.";
        } else {
            return redirect()->route('members')->with('error', 'Invalid payment duration');
        }

        // echo "<pre>";
        // echo "Member DEtails:";
        // print_r($member->toArray());

        // echo "Payment Details:";
        // print_r($payment->toArray());

        // echo "Paid Content:";
        // echo $paidContent;

        // echo "</pre>";
        // exit;

        // Send Email to member
        if (!empty($member->email)) {
            try {
                // Mail::to($member->email)->send(new PaymentSuccessMail($member, $payment));
                Mail::to($member->email)->send(new PaymentSuccessMail($member, $payment, $paidContent, $subject));
            } catch (\Exception $e) {
                \Log::error('Payment email failed: ' . $e->getMessage());
            }
        }

        return redirect()->route('members')->with('success', 'Payment recorded successfully');
    }

    /**
     * Clean amount string by removing currency symbols and commas
     */
    private function cleanAmount($amount)
    {
        // Remove currency symbols (₹, $, etc.) and commas
        $cleanAmount = preg_replace('/[^\d.]/', '', $amount);

        // Convert to decimal
        return (float) $cleanAmount;
    }
}
