<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\Subscription\PaymentApprovalService;
use App\Domain\Subscription\UsageService;
use App\Enums\PaymentProofStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\SubmitPaymentProofRequest;
use App\Models\Plan;
use App\Models\SubscriptionPayment;
use App\Support\Tenancy;
use App\Domain\Files\PatientFileService;
use Illuminate\Support\Facades\Storage;

class BillingController extends Controller
{
    public function index(Tenancy $tenancy, UsageService $usage)
    {
        $tenant = $tenancy->get();
        $subscription = $tenant->subscription?->load('plan');

        return view('tenant.billing', [
            'tenant' => $tenant,
            'subscription' => $subscription,
            'plan' => $subscription?->plan ?? Plan::where('is_active', true)->first(),
            'payments' => SubscriptionPayment::where('tenant_id', $tenant->id)
                ->latest()->limit(10)->get(),
            'usage' => $usage->status($tenant, 'wa_messages'),
            'staffUsage' => $usage->staff($tenant),
            'dentistUsage' => $usage->dentists($tenant),
            'storageUsage' => $usage->storage($tenant),
            'trialDaysLeft' => $subscription && $subscription->status === 'trialing' && $subscription->current_period_ends_at
                ? max(0, (int) ceil(now()->diffInDays($subscription->current_period_ends_at, false)))
                : null,
            'paddleLink' => config('services.paddle.checkout_url'),
        ]);
    }

    /** Submit a Zain Cash / SuperQi proof for super-admin review. */
    public function submitProof(SubmitPaymentProofRequest $request, Tenancy $tenancy, PaymentApprovalService $approvals)
    {
        $tenant = $tenancy->get();
        $plan = $tenant->subscription?->plan ?? Plan::where('is_active', true)->firstOrFail();

        $path = $request->file('proof')->store(
            "tenants/{$tenant->id}/billing-proofs", PatientFileService::DISK
        );

        $payment = SubscriptionPayment::create([
            'tenant_id' => $tenant->id,
            'subscription_id' => $tenant->subscription?->id,
            'plan_id' => $plan->id,
            'gateway' => $request->gateway,
            'amount' => $plan->price_monthly_iqd * $request->integer('period_months'),
            'currency' => 'IQD',
            'status' => PaymentProofStatus::Pending,
            'period_months' => $request->integer('period_months'),
            'proof_path' => $path,
            'proof_reference' => $request->proof_reference,
        ]);

        $approvals->submitted($payment, $request->ip());
        app(\App\Domain\Subscription\ActivityLogger::class)->log(
            'payment.submitted',
            __('Payment proof uploaded (:gateway)', ['gateway' => $payment->gateway->label()]),
            $payment, $tenant->id, $request->user()->id,
            ['amount' => $payment->amount, 'months' => $payment->period_months], $request->ip(),
        );

        return back()->with('status', __('Payment proof submitted. We will review it shortly.'));
    }

    /** Owner views their own uploaded proof. */
    public function proof(SubscriptionPayment $payment)
    {
        abort_unless($payment->tenant_id === app(Tenancy::class)->id(), 404);
        abort_unless(auth()->user()->can('billing.manage'), 403);
        abort_unless($payment->proof_path && Storage::disk(PatientFileService::DISK)->exists($payment->proof_path), 404);

        return Storage::disk(PatientFileService::DISK)->response($payment->proof_path);
    }
}
