<?php

namespace App\Services;

use App\Models\Transaction;
use App\Models\Subscription;
use App\Models\ProductPromotion;
use App\Models\PromotionPackage;
use App\Models\Plan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use App\Mail\SubscriptionActivated;
use App\Mail\PromotionActivated;

class TransactionService
{
    /**
     * Activate a transaction (Subscription or Promotion)
     */
    public function activateTransaction(Transaction $transaction)
    {
        if ($transaction->status === 'success') {
            return; // Already activated
        }

        DB::transaction(function () use ($transaction) {
            if ($transaction->transaction_type === 'subscription') {
                $this->activateSubscription($transaction);
            } elseif ($transaction->transaction_type === 'promotion') {
                $this->activatePromotion($transaction);
            }

            $transaction->update([
                'status' => 'success',
                'payment_completed_at' => now(),
            ]);
        });
    }

    /**
     * Activate Subscription
     */
    protected function activateSubscription(Transaction $transaction)
    {
        $metadata = $transaction->metadata;
        $planId = $metadata['plan_id'] ?? null;
        
        if (!$planId) {
            throw new \Exception("Plan ID not found in transaction metadata");
        }

        $plan = Plan::findOrFail($planId);
        $seller = $transaction->seller;

        // Deactivate current active subscription
        $seller->subscription()->active()->update(['status' => 'expired']);

        // Create new subscription
        $subscription = Subscription::create([
            'seller_id' => $seller->id,
            'plan_id' => $plan->id,
            'start_date' => now(),
            'end_date' => now()->addDays($plan->duration_days),
            'status' => 'active',
            'payment_id' => $transaction->payment_id,
            'payment_method' => $transaction->payment_method,
        ]);

        // Link subscription to seller
        $seller->update(['subscription_id' => $subscription->id]);

        // Update transaction reference
        $transaction->update(['reference_id' => $subscription->id]);

        // Send Email
        // Send Email via Dynamic Service
        \App\Services\EmailService::send('subscription-activated', $seller->user->email, [
            'plan_name' => $plan->name,
            'end_date' => $subscription->end_date->format('F j, Y'),
            'seller_name' => $seller->user->name,
        ]);

        // Send In-App Notification
        \App\Services\NotificationService::subscriptionActivated(
            $seller->user->id,
            $plan->name,
            $subscription->end_date->format('F j, Y')
        );
    }

    /**
     * Activate Promotion
     */
    protected function activatePromotion(Transaction $transaction)
    {
        $metadata = $transaction->metadata;
        $packageId = $metadata['package_id'] ?? null;
        $productIds = $metadata['product_ids'] ?? [];

        if (!$packageId) {
            throw new \Exception("Package ID not found in transaction metadata");
        }

        $package = PromotionPackage::findOrFail($packageId);
        $seller = $transaction->seller;

        $startDate = now();
        $endDate = now()->addDays($package->duration_days);
        $promotionIds = [];

        foreach ($productIds as $productId) {
            $promotion = ProductPromotion::create([
                'product_id' => $productId,
                'seller_id' => $seller->id,
                'package_id' => $package->id,
                'status' => 'active',
                'start_date' => $startDate,
                'end_date' => $endDate,
                'price_paid' => $package->price,
                'payment_method' => $transaction->payment_method,
            ]);
            $promotionIds[] = $promotion->id;
        }

        // Update transaction reference (first promotion)
        if (!empty($promotionIds)) {
            $transaction->update(['reference_id' => $promotionIds[0]]);
        }

        // Send Email
        // Send Email via Dynamic Service
        \App\Services\EmailService::send('promotion-activated', $seller->user->email, [
            'package_name' => $package->name,
            'seller_name' => $seller->user->name,
            'price' => $package->price,
        ]);
    }
}
