<?php

namespace App\Http\Controllers;

use App\Models\Installment;
use App\Models\Payment;
use App\Http\Requests\PaymentRequest;
use Illuminate\Http\Request;

class InstallmentController extends Controller
{
    public function index(Request $request)
    {
        $query = Installment::with(['sale.customer'])
            ->orderBy('due_date');

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

        // Filter by date range
        if ($request->has('start_date') && $request->has('end_date')) {
            $query->whereBetween('due_date', [
                $request->start_date,
                $request->end_date
            ]);
        }

        // Filter by overdue
        if ($request->has('overdue')) {
            $query->overdue();
        }

        $installments = $query->paginate(20);
        
        $stats = [
            'total_pending' => Installment::pending()->count(),
            'total_overdue' => Installment::overdue()->count(),
            'total_due_this_month' => Installment::dueThisMonth()->count(),
        ];
        
        return view('installments.index', compact('installments', 'stats'));
    }

    public function overdue(Request $request)
{
    $query = Installment::with(['sale.customer'])
        ->overdue()
        ->orderBy('due_date');
    
    if ($request->filled('search')) {
        $search = $request->search;
        $query->whereHas('customer', function($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('phone', 'like', "%{$search}%");
        });
    }
    
    $installments = $query->paginate(20);
    
    return view('installments.overdue', compact('installments'));
}

    public function show(Installment $installment)
    {
        $installment->load(['sale.customer', 'payments.receiver']);
        
        return view('installments.show', compact('installment'));
    }

    public function pay(Installment $installment)
    {
        if ($installment->status === 'paid') {
            return back()->with('error', 'This installment is already paid.');
        }

        $installment->load(['sale.customer']);
        
        // Calculate late fee if overdue
        $lateFee = 0;
        if ($installment->is_overdue) {
            $lateFee = $installment->late_fee_amount;
        }
        
        return view('installments.pay', compact('installment', 'lateFee'));
    }

    public function processPayment(PaymentRequest $request, Installment $installment)
    {
        if ($installment->status === 'paid') {
            return back()->with('error', 'This installment is already paid.');
        }

        $validated = $request->validated();
        
        // Validate payment amount
        if ($validated['amount'] > $installment->due_amount) {
            return back()->with('error', 'Payment amount cannot exceed due amount.');
        }

        // Process payment
        $installment->addPayment($validated['amount'], $validated['late_fee'] ?? 0);
        
        // Create payment record
        $payment = Payment::create([
            'installment_id' => $installment->id,
            'sale_id' => $installment->sale_id,
            'customer_id' => $installment->sale->customer_id,
            'payment_no' => Payment::generatePaymentNo(),
            'payment_type' => $validated['amount'] == $installment->amount ? 'installment' : 'partial',
            'amount' => $validated['amount'] + ($validated['late_fee'] ?? 0),
            'payment_method' => $validated['payment_method'],
            'bank_name' => $validated['bank_name'] ?? null,
            'check_no' => $validated['check_no'] ?? null,
            'check_date' => $validated['check_date'] ?? null,
            'transaction_id' => $validated['transaction_id'] ?? null,
            'mobile_banking_provider' => $validated['mobile_banking_provider'] ?? null,
            'mobile_banking_number' => $validated['mobile_banking_number'] ?? null,
            'notes' => $validated['notes'] ?? null,
            'payment_date' => $validated['payment_date'] ?? now(),
            'received_by' => auth()->id(),
        ]);

        // Send SMS notification
        if ($request->send_sms) {
            $this->sendPaymentConfirmationSms($installment, $payment);
        }

        return redirect()->route('installments.show', $installment)
            ->with('success', 'Payment processed successfully! Receipt: ' . $payment->payment_no);
    }

    public function sendReminder(Installment $installment)
    {
        if ($installment->status === 'paid') {
            return back()->with('error', 'Cannot send reminder for paid installment.');
        }

        try {
            $daysUntilDue = now()->diffInDays($installment->due_date, false);
            
            $message = "Dear {$installment->sale->customer->name}, ";
            $message .= "Your installment #{$installment->installment_no} of ৳{$installment->amount} ";
            
            if ($daysUntilDue > 0) {
                $message .= "is due in {$daysUntilDue} days (Due: {$installment->due_date->format('d/m/Y')}). ";
            } else {
                $message .= "was due on {$installment->due_date->format('d/m/Y')}. ";
                $message .= "Please pay immediately to avoid late fees. ";
            }
            
            $message .= "Walton Plaza";
            
            // Send SMS logic here (using your SMS gateway)
            // $this->smsService->send($installment->sale->customer->phone, $message);
            
            // Log SMS
            \App\Models\SmsLog::create([
                'customer_id' => $installment->sale->customer_id,
                'phone' => $installment->sale->customer->phone,
                'message_type' => 'installment_reminder',
                'message' => $message,
                'status' => 'sent',
                'sent_at' => now(),
            ]);
            
            return back()->with('success', 'Reminder sent successfully!');
            
        } catch (\Exception $e) {
            return back()->with('error', 'Failed to send reminder: ' . $e->getMessage());
        }
    }

    private function sendPaymentConfirmationSms($installment, $payment)
    {
        try {
            $customer = $installment->sale->customer;
            
            $message = "Dear {$customer->name}, ";
            $message .= "Payment of ৳{$payment->amount} received for installment #{$installment->installment_no}. ";
            $message .= "Receipt: {$payment->payment_no}. ";
            $message .= "Remaining due: ৳{$installment->due_amount}. ";
            $message .= "Thank you! Walton Plaza";
            
            // Send SMS logic here
            // $this->smsService->send($customer->phone, $message);
            
            // Log SMS
            \App\Models\SmsLog::create([
                'customer_id' => $customer->id,
                'phone' => $customer->phone,
                'message_type' => 'payment_confirmation',
                'message' => $message,
                'status' => 'sent',
                'sent_at' => now(),
            ]);
            
        } catch (\Exception $e) {
            // Log error but don't fail the payment
            \Log::error('Failed to send payment confirmation SMS: ' . $e->getMessage());
        }
    }
}