<?php

namespace MtcPharmacy\Subscriptions\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Mtc\Shop\Item as ShopItem;
use MtcPharmacy\Subscriptions\Classes\Subscription;

/**
 * Send emails to members whose subscription assessments are expiring soon.
 *
 * Example: php artisan subscriptions:send_expiring_assessment_email
 */


class SendExpiringAssessmentEmailCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscriptions:send_expiring_assessment_email';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send email for expiring assessment';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info(__METHOD__);

        $active_subscriptions = Subscription::active()
            ->whereNotNull('next_issue_date')
            ->whereNotNull('expiry_date')
            ->where('is_assessment_updated', 1)
            ->where('expiry_date', '>=', Carbon::now())
            ->whereDate('expiry_date', '<=', Carbon::now()->addDays(7))
            ->get();

        if (count($active_subscriptions) === 0) {
            $this->info('Done.');
            return;
        }

        foreach ($active_subscriptions as $sub) {
            // Skip subscriptions whose products don't require an assessment
            if (!$this->subscriptionRequiresAssessment($sub)) {
                $this->info("Skipping subscription #{$sub->id} - products do not require assessment");
                $sub->is_assessment_updated = 0;
                $sub->save();
                continue;
            }

            $this->info('Sent Email to ' . $sub->member->email . ' for #' . $sub->id);
            // Send an email for assessment
            $sub->emailSubscriptionUpdates(
                'Please confirm your assessment answers',
                'update_assessment'
            );

            $sub->is_assessment_updated = 0;
            $sub->save();
        }

    }

    /**
     * Check if any item in the subscription requires an assessment.
     * Mirrors the add-to-basket logic: product_type must be doctor/pharmacy,
     * assessment forms not disabled, and a form_id on the item or its category.
     */
    private function subscriptionRequiresAssessment(Subscription $subscription): bool
    {
        foreach ($subscription->items as $subscriptionItem) {
            $shopItem = $subscriptionItem->shop_item;

            if (!$shopItem) {
                continue;
            }

            if (!in_array($shopItem->product_type, [ShopItem::TYPE_DOCTOR, ShopItem::TYPE_PHARMACY])) {
                continue;
            }

            if ($shopItem->disable_assessment_forms) {
                continue;
            }

            // Check item-level form_id first, then category-level
            if (!empty($shopItem->form_id) && (int) $shopItem->form_id > 0) {
                return true;
            }

            $mainCategory = $shopItem->getMainCategory();
            if ($mainCategory && !empty($mainCategory->form_id) && (int) $mainCategory->form_id > 0) {
                return true;
            }
        }

        return false;
    }

}
