<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;

class InternetPayment extends Model
{
    protected $fillable = [
        'station_id',
        'vendor_id',
        'account_number',
        'amount',
        'previous_balance',
        'billing_month',
        'due_date',
        'payment_date',
        'mpesa_receipt',
        'transaction_id',
        'status',
        'invoice_notes',
        'payment_method',
        'last_reminder_sent',
        'reminder_count',
    ];

    protected $casts = [
        'billing_month' => 'date:Y-m-d',
        'due_date' => 'date:Y-m-d',
        'payment_date' => 'date:Y-m-d',
        'amount' => 'decimal:2',
        'previous_balance' => 'decimal:2',
        'total_due' => 'decimal:2',
        'last_reminder_sent' => 'datetime',
        'reminder_count' => 'integer',
    ];

    protected $appends = ['is_overdue', 'days_overdue', 'is_due_soon'];

    protected $attributes = [
        'previous_balance' => 0.00,
        // 'total_due' => 0.00, // REMOVE THIS - DB calculates it
        'amount' => 0.00,
        'status' => 'pending'
    ];

    // accessor for reading the value
    public function getTotalDueAttribute()
    {
        // The database calculates this, just return the attribute
        return $this->attributes['total_due'] ?? 0.00;
    }

    public function station(): BelongsTo
    {
        return $this->belongsTo(Station::class, 'station_id');
    }

    public function provider(): BelongsTo
    {
        return $this->belongsTo(InternetProvider::class, 'vendor_id');
    }

    public function getIsOverdueAttribute()
    {
        if ($this->status === 'paid' || $this->status === 'cancelled') {
            return false;
        }

        $dueDate = $this->due_date instanceof Carbon ? $this->due_date : Carbon::parse($this->due_date);
        return Carbon::now()->gt($dueDate);
    }

    public function getDaysOverdueAttribute()
    {
        if (!$this->is_overdue) {
            return 0;
        }

        $dueDate = $this->due_date instanceof Carbon ? $this->due_date : Carbon::parse($this->due_date);
        return Carbon::now()->diffInDays($dueDate);
    }

    public function getIsDueSoonAttribute()
    {
        if ($this->status !== 'pending') {
            return false;
        }

        $dueDate = $this->due_date instanceof Carbon ? $this->due_date : Carbon::parse($this->due_date);
        $dueSoonDate = Carbon::now()->addDays(3);

        return $dueDate->lte($dueSoonDate) && $dueDate->gte(Carbon::now());
    }

    // Mutators - REMOVE calls to calculateTotalDue()
    public function setAmountAttribute($value)
    {
        $this->attributes['amount'] = (float) $value;
    }

    public function setPreviousBalanceAttribute($value)
    {
        $this->attributes['previous_balance'] = (float) $value;
    }

    public function setBillingMonthAttribute($value)
    {
        $this->attributes['billing_month'] = Carbon::parse($value)->format('Y-m-d');
    }

    public function setDueDateAttribute($value)
    {
        $this->attributes['due_date'] = Carbon::parse($value)->format('Y-m-d');
    }

    public function setPaymentDateAttribute($value)
    {
        if ($value) {
            $this->attributes['payment_date'] = Carbon::parse($value)->format('Y-m-d');
        } else {
            $this->attributes['payment_date'] = null;
        }
    }

    public function generateReminderMessage()
    {
        $provider = $this->provider;
        $station = $this->station;

        $dueDate = Carbon::parse($this->due_date);
        $billingMonth = Carbon::parse($this->billing_month);

        // Get total_due from the model attribute
        $totalDue = $this->total_due;

        $message = "Dear {$station->contact_person},\n\n";
        $message .= "Internet Service Payment Reminder\n";
        $message .= "==================================\n";
        $message .= "Provider: {$provider->name}\n";
        $message .= "Account: {$this->account_number}\n";
        $message .= "Station: {$station->name} - {$station->location}\n";
        $message .= "Billing Month: {$billingMonth->format('F Y')}\n";
        $message .= "Amount Due: KES " . number_format((float) $totalDue, 2) . "\n";
        $message .= "Due Date: {$dueDate->format('d/m/Y')}\n\n";

        if ($provider->paybill_number) {
            $message .= "Pay via M-Pesa:\n";
            $message .= "1. Go to Lipa na M-PESA\n";
            $message .= "2. Select Pay Bill\n";
            $message .= "3. Business No: {$provider->paybill_number}\n";
            $message .= "4. Account No: {$this->account_number}\n";
            $message .= "5. Amount: KES " . number_format((float) $totalDue, 2) . "\n\n";
        }

        $message .= "Contact Support: {$provider->support_contact}\n";
        if ($provider->billing_email) {
            $message .= "Email: {$provider->billing_email}\n\n";
        }

        if ($this->is_overdue) {
            $message .= "⚠️ OVERDUE: This payment is {$this->days_overdue} day(s) overdue.\n";
        } elseif ($this->is_due_soon) {
            $message .= "⏰ REMINDER: Payment due in " . Carbon::now()->diffInDays($dueDate) . " day(s).\n";
        }

        $message .= "\nThank you for your prompt payment.";

        return $message;
    }

    /**
     * Generate a concise reminder message (shorter version)
     *
     * @return string
     */
    public function generateShortReminderMessage()
    {
        $dueDate = $this->due_date instanceof Carbon ? $this->due_date : Carbon::parse($this->due_date);
        $today = Carbon::today();

        $daysUntilDue = $today->diffInDays($dueDate);

        if ($dueDate->isToday()) {
            $timeFrame = "DUE TODAY";
        } elseif ($dueDate->isTomorrow()) {
            $timeFrame = "DUE TOMORROW";
        } else {
            $timeFrame = "DUE IN {$daysUntilDue} DAYS";
        }

        $formattedAmount = number_format($this->total_due, 2);

        return "{$timeFrame}: KES {$formattedAmount} - {$this->provider->name}/{$this->station->name} - Acct: {$this->account_number}";
    }

    /**
     * Generate an SMS-friendly reminder message
     *
     * @return string
     */
    public function generateSmsReminderMessage()
    {
        $dueDate = $this->due_date instanceof Carbon ? $this->due_date : Carbon::parse($this->due_date);
        $today = Carbon::today();

        $daysUntilDue = $today->diffInDays($dueDate);

        if ($dueDate->isToday()) {
            $timeFrame = "today";
        } elseif ($dueDate->isTomorrow()) {
            $timeFrame = "tomorrow";
        } else {
            $timeFrame = "in {$daysUntilDue} days";
        }

        $formattedAmount = number_format($this->total_due, 2);

        return "Internet Payment Reminder: KES {$formattedAmount} due {$timeFrame} for {$this->station->name}. Pay via {$this->provider->paybill_number} (Acc: {$this->account_number}).";
    }

    public function mpesaTransactions()
    {
        return $this->hasMany(MpesaTransaction::class, 'payment_id');
    }

    public function notificationLogs()
    {
        return $this->hasMany(NotificationLog::class, 'payment_id')->where('payment_type', 'internet');
    }

}
