<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Product;
use App\Models\Notification;
use App\Models\Payment;
use App\Models\User;
use Carbon\Carbon;


class CashPaymentFollowup extends Command
{
    protected $signature = 'cash:payment-followup';
    protected $description = 'Send follow-up notification & mail for pending cash payment after 15 days';

    public function handle()
    {
        $environment_data = getEnvironmentData();  
        $wait_for_cash_payment_days = $environment_data['WAIT_FOR_CASH_PAYMENT_DAYS'];
        $dateLimit = Carbon::now('UTC')->subDays($wait_for_cash_payment_days);

        $payments = Payment::with('user')
            ->where('payment_status', '=', 'pending')
            ->whereDate('created_at', '<=', $dateLimit)
            ->get();

        foreach ($payments as $payment) {
            if (!$payment->user) {
                continue;
            }

            $message = "This is a reminder to complete your cash payment for the product you purchased.";

            // Save Notification
            Notification::create([
                'user_id' => $payment->user->id,
                'title'   => "Cash Payment Reminder",
                'message' => $message
            ]);

            // Push notification
            pushNotification($payment->user->id , $message);
        }

        \Log::info('Cash payment follow-up notifications sent successfully.');
    }
}