<?php

namespace App\Http\Controllers;

use App\Models\Plan;
use App\Models\Subscription;
use App\Services\SubscriptionService;
use App\Services\PaymentService;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    protected $subService;
    protected $payService;

    public function __construct(SubscriptionService $subService, PaymentService $payService)
    {
        $this->subService = $subService;
        $this->payService = $payService;
    }

    public function required()
    {
        $plans = Plan::where('role_type', auth()->user()->role->name)->where('is_active', true)->get();
        return view('subscription.required', compact('plans'));
    }

    public function checkout(Plan $plan)
    {
        return view('subscription.checkout', compact('plan'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'plan_id' => 'required|exists:plans,id',
            'amount' => 'required|numeric',
            'sender_name' => 'required|string',
            'transfer_date' => 'required|date',
            'proof' => 'required|image|max:2048',
        ]);

        $plan = Plan::findOrFail($request->plan_id);
        $subscription = $this->subService->createPending(auth()->user(), $plan);
        
        $this->payService->submitProof(
            $subscription,
            $request->file('proof'),
            $request->amount,
            $request->sender_name,
            $request->transfer_date
        );

        return redirect()->route('dashboard')->with('success', 'Bukti transfer berhasil diunggah. Menunggu verifikasi admin.');
    }
}
