<?php
/**
 * This command updates the assessment_id in the subscription_items table where assessment_id is 0.
 *
 * @author Ashok Basnet <ashok.basnet@mtc.co.uk>
 * @since 07/05/2025
 */

namespace MtcPharmacy\Subscriptions\Console\Commands;

use Illuminate\Console\Command;
use MtcPharmacy\Subscriptions\Classes\SubscriptionItem;
use Illuminate\Support\Facades\Log;

class UpdateAssessmentIdInSubscriptionItemsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'subscriptions:update-assessment-id-in-items {--dry-run : Run without making changes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update assessment_id in subscription_items table where assessment_id is 0';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Starting to update assessment_id in subscription_items where assessment_id = 0...');
        $isDryRun = $this->option('dry-run');
        if ($isDryRun) {
            $this->warn('DRY RUN MODE: No database changes will be made');
        }

        $items = SubscriptionItem::where('assessment_id', 0)->get();
        $this->info('Found ' . $items->count() . ' subscription_items with assessment_id = 0');

        $updatedCount = 0;
        foreach ($items as $item) {
            $this->info('Processing subscription_item #' . $item->id);
            // Try to get the assessment_id from the parent subscription (if possible)
            $subscription = $item->subscription;

            if ($subscription) {

                // Get assessment_id from the first order item
                $newAssessmentId = null;
                $order = $subscription->orders()->first();
                if ($order) {
                    $order_item = $order->items()->where('has_requested_subscription', 1)->first();
                    if ($order_item) {
                        $newAssessmentId = $order_item->assessment_id;
                    }
                }
                if ($newAssessmentId && $newAssessmentId != 0) {
                    if (!$isDryRun) {
                        $item->assessment_id = $newAssessmentId;
                        $item->save();
                    }
                    $updatedCount++;
                    $this->info("Updated subscription_item #{$item->id} with assessment_id {$newAssessmentId}");
                } else {
                    $this->warn("Could not find valid assessment_id for subscription_item #{$item->id}");
                }
            } else {
                $this->warn("No parent subscription found for subscription_item #{$item->id}");
            }
        }

        $this->info("Completed. Updated $updatedCount subscription_items.");
        return 0;
    }
}