<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ManualPayment;
use App\Services\SubscriptionActivationService;
use App\Services\AuditLogService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PaymentReviewController extends Controller
{
    protected $activationService;
    protected $auditLog;

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

    public function index()
    {
        $payments = ManualPayment::where('payment_status', 'pending')
            ->with(['subscription.user', 'subscription.plan'])
            ->latest()
            ->paginate(20);

        return view('admin.payment-reviews.index', compact('payments'));
    }

    public function approve(Request $request, ManualPayment $payment)
    {
        $request->validate(['notes' => 'nullable|string']);
        
        $this->activationService->activate($payment->id, auth()->id(), $request->notes);

        return back()->with('success', 'Pembayaran telah disetujui dan paket layanan pengguna kini aktif.');
    }

    public function reject(Request $request, ManualPayment $payment)
    {
        $request->validate(['notes' => 'required|string']);
        
        $this->activationService->reject($payment->id, auth()->id(), $request->notes);

        return back()->with('info', 'Pembayaran ditolak. Pengguna akan menerima notifikasi alasan penolakan.');
    }

    /**
     * Securely download/view the payment proof file.
     */
    public function showProof(ManualPayment $payment)
    {
        // Admin only check is handled by role middleware on the group
        if (!Storage::disk('local')->exists($payment->proof_path)) {
            abort(404, 'Bukti bayar tidak ditemukan.');
        }

        return Storage::disk('local')->response($payment->proof_path);
    }
}
