<?php

namespace App\Services;

use App\Models\ManualPayment;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class SubscriptionActivationService
{
    protected $auditLog;
    protected $notification;

    public function __construct(AuditLogService $auditLog, NotificationService $notification)
    {
        $this->auditLog = $auditLog;
        $this->notification = $notification;
    }

    /**
     * Activate a subscription based on an approved payment.
     */
    public function activate(int $paymentId, int $reviewerId, ?string $notes = null): bool
    {
        return DB::transaction(function () use ($paymentId, $reviewerId, $notes) {
            $payment = ManualPayment::with('subscription.user')->findOrFail($paymentId);
            $subscription = $payment->subscription;
            $user = $subscription->user;

            $payment->update([
                'payment_status' => 'approved',
                'reviewed_by' => $reviewerId,
                'reviewed_at' => now(),
                'review_notes' => $notes
            ]);

            $subscription->update([
                'subscription_status' => 'active',
                'start_date' => now(),
                'end_date' => now()->addDays($subscription->plan->duration_days)
            ]);

            // Activate User Account
            $user->update(['account_status' => 'active']);

            $this->auditLog->log('PAYMENT_APPROVED', $payment, null, ['notes' => $notes]);
            $this->notification->notify($user, 'Pembayaran Disetujui', 'Selamat! Pembayaran Anda telah dikonfirmasi dan akun Anda kini aktif.', 'success', route('dashboard'));

            return true;
        });
    }

    /**
     * Reject a payment.
     */
    public function reject(int $paymentId, int $reviewerId, string $notes): bool
    {
        $payment = ManualPayment::with('subscription.user')->findOrFail($paymentId);
        
        $payment->update([
            'payment_status' => 'rejected',
            'reviewed_by' => $reviewerId,
            'reviewed_at' => now(),
            'review_notes' => $notes
        ]);

        $this->auditLog->log('PAYMENT_REJECTED', $payment, null, ['notes' => $notes]);
        $this->notification->notify($payment->subscription->user, 'Pembayaran Ditolak', 'Mohon maaf, pembayaran Anda ditolak dengan alasan: ' . $notes, 'danger');

        return true;
    }
}
