<?php

namespace App\Services;

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

class PaymentService
{
    protected $subscriptionService;

    public function __construct(SubscriptionService $subscriptionService)
    {
        $this->subscriptionService = $subscriptionService;
    }

    /**
     * Submit payment proof.
     */
    public function submitProof(Subscription $subscription, $file, $amount, $senderName, $transferDate)
    {
        $path = $file->store('proofs', 'public');

        return ManualPayment::create([
            'subscription_id' => $subscription->id,
            'amount' => $amount,
            'transfer_date' => $transferDate,
            'sender_name' => $senderName,
            'proof_path' => $path,
            'payment_status' => 'pending',
        ]);
    }

    /**
     * Approve payment.
     */
    public function approve(ManualPayment $payment, User $reviewer)
    {
        return DB::transaction(function () use ($payment, $reviewer) {
            $payment->update([
                'payment_status' => 'approved',
                'reviewed_by' => $reviewer->id,
                'reviewed_at' => now(),
            ]);

            // Activate linked subscription
            $this->subscriptionService->activate($payment->subscription);

            // Ensure user account is active
            $payment->subscription->user->update(['account_status' => 'active']);

            return $payment;
        });
    }

    /**
     * Reject payment.
     */
    public function reject(ManualPayment $payment, string $reason, User $reviewer)
    {
        return $payment->update([
            'payment_status' => 'rejected',
            'review_notes' => $reason,
            'reviewed_by' => $reviewer->id,
            'reviewed_at' => now(),
        ]);
    }

    public function getPending()
    {
        return ManualPayment::with(['subscription.user', 'subscription.plan'])
            ->where('payment_status', 'pending')
            ->get();
    }
}
