<?php

namespace App\Services;

use App\Models\ManualPayment;
use App\Models\Subscription;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\UploadedFile;

class ManualPaymentService
{
    protected $auditLog;
    protected $notification;

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

    /**
     * Submit a manual payment proof with secure private storage.
     */
    public function submitProof($subscription, array $data, UploadedFile $file): ManualPayment
    {
        // Use local private storage for payment proofs
        $path = $file->storeAs(
            'private/payments/proofs/' . $subscription->user_id,
            time() . '_' . $file->getClientOriginalName()
        );
        
        $payment = ManualPayment::create([
            'subscription_id' => $subscription->id,
            'amount' => $data['amount'],
            'transfer_date' => $data['transfer_date'],
            'sender_name' => $data['sender_name'],
            'proof_path' => $path,
            'payment_status' => 'pending',
            'review_notes' => $data['review_notes'] ?? null,
        ]);

        $this->auditLog->log('PAYMENT_UPLOADED', $payment);
        
        // Notify all admins about the new payment review request
        $this->notification->notifyAdmin(
            'Review Pembayaran Baru', 
            "User {$subscription->user->name} telah mengunggah bukti bayar Rp " . number_format($data['amount'], 0, ',', '.'),
            'warning', 
            route('admin.payment-reviews.index')
        );

        return $payment;
    }

    public function submitPayment(array $data, int $subscriptionId): ManualPayment
    {
        $subscription = Subscription::with('user')->findOrFail($subscriptionId);
        return $this->submitProof($subscription, $data, $data['proof_file']);
    }

    /**
     * Get pending payments for admin review.
     */
    public function getPending()
    {
        return ManualPayment::where('payment_status', 'pending')
            ->with(['subscription.user', 'subscription.plan'])
            ->latest()
            ->paginate(20);
    }
}
