<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;

class PaymentController extends Controller
{
    public function index(Request $request)
    {
        $query = Payment::with('member')->latest();

        // Search
        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('member', function($q) use ($search){
                $q->where('first_name', 'like', "%$search%")
                  ->orWhere('surname', 'like', "%$search%");
            })->orWhere('fingerprint_id', 'like', "%$search%");
        }

        // Filters
        if ($request->filled('status')) {
            if ($request->status == 'active') $query->whereDate('next_payment_date', '>=', Carbon::today());
            elseif ($request->status == 'expired') $query->whereDate('next_payment_date', '<', Carbon::today());
        }

        if ($request->filled('membership_type')) $query->where('membership_type', $request->membership_type);

        $payments = $query->get()->unique('member_id'); // Only latest per member

        return view('payments.index', compact('payments'));
    }

    public function history($memberId)
    {
        $member = Member::findOrFail($memberId);
        $payments = Payment::where('member_id', $member->id)->latest()->get();
        return view('payments.history', compact('member', 'payments'));
    }

    public function renewAjax(Request $request, $memberId)
    {
        $request->validate([
            'renew_date' => 'required|date',
            'expiry_date' => 'required|date|after_or_equal:renew_date',
            'payment_type' => 'required|string',
            'package_duration' => 'required|string',
        ]);

        try {
            $member = Member::findOrFail($memberId);

            $renewDate = Carbon::parse($request->renew_date);
            $expiryDate = Carbon::parse($request->expiry_date);

            // Amount based on package_duration & membership_type
            $amounts = [
                'Male' => [
                    '1 Month'=>4000, '3 Months'=>10000, '6 Months'=>20000, '12 Months'=>28000, 'Personal Training'=>25000
                ],
                'Female'=>[
                    '1 Month'=>3500, '3 Months'=>8000, '6 Months'=>18000, '12 Months'=>25000, 'Personal Training'=>25000
                ],
                'Couple'=>[
                    '1 Month'=>7000, '3 Months'=>17500, '6 Months'=>35000, '12 Months'=>50000
                ],
                'Family'=>[
                    '1 Month'=>10000, '3 Months'=>25000, '6 Months'=>50000, '12 Months'=>75000
                ],
            ];

            $amount = $amounts[$member->membership_type][$request->package_duration] ?? 0;

            // Update member next payment and expiry
            $member->update([
                'approval_date'=>$renewDate,
                'expiry_date'=>$expiryDate,
                'next_payment_date'=>$expiryDate,
            ]);

            // Create Payment record
            $payment = Payment::create([
                'member_id'=>$member->id,
                'fingerprint_id'=>$member->fingerprint_id,
                'membership_type'=>$member->membership_type,
                'package_type'=>$request->package_duration,
                'amount'=>$amount,
                'payment_date'=>$renewDate,
                'payment_type'=>$request->payment_type,
                'expiry_date'=>$expiryDate,
                'next_payment_date'=>$expiryDate,
            ]);

            // Send SMS
            $message = "Hi {$member->first_name}! 🎉\n\nThank you for renewing your membership at Iron Ground Fitness Club. \nYour membership is now valid from {$renewDate->format('d/m/Y')} to {$expiryDate->format('d/m/Y')}.\nStay strong, stay motivated, and see you at the gym!";
            $this->sendSms($member->mobile, $message);

            return response()->json(['success'=>true, 'message'=>'Membership renewed successfully!']);

        } catch (\Exception $e) {
            return response()->json(['success'=>false, 'message'=>$e->getMessage()]);
        }
    }

    private function sendSms($phone, $message)
    {
        try {
            $res = Http::get("https://www.textit.biz/sendmsg/", [
                'id' => '94770899955',
                'pw' => '2104',
                'to' => $phone,
                'text' => $message,
            ]);
            return str_contains($res->body(), 'OK');
        } catch (\Exception $e) {
            return false;
        }
    }

    public function destroy($paymentId)
    {
        $payment = Payment::findOrFail($paymentId);
        $payment->delete();
        return redirect()->back()->with('success','Payment deleted successfully!');
    }
}
