<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Organization;
use App\Services\Billing\BillingClient;
use App\Services\Care\CarePermissions;
use App\Services\Care\PlanService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class ProController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request, PlanService $plans): View
    {
        $organization = $this->organization($request);
        $canManage = app(CarePermissions::class)->can($this->member($request), 'settings.manage');
        $settings = $organization->settings ?? [];
        $expiresAt = ! empty($settings['plan_expires_at'])
            ? Carbon::parse($settings['plan_expires_at'])
            : null;
        $planKey = $plans->planKey($organization);
        $branchCount = max(1, $plans->activeBranchCount($organization));
        $proTotal = $plans->proPriceTotalMinor($organization);
        $enterpriseTotal = $plans->enterprisePriceMinor($organization);

        return view('care.pro.index', [
            'organization' => $organization,
            'planKey' => $planKey,
            'isPro' => $planKey === 'pro',
            'isEnterprise' => $planKey === 'enterprise',
            'hasPaidPlan' => $plans->hasPaidPlan($organization),
            'canManage' => $canManage,
            'proPricePerBranchMinor' => $plans->proPricePerBranchMinor(),
            'proPriceMinor' => $proTotal,
            'enterprisePricePerBranchMinor' => $plans->enterprisePricePerBranchMinor(),
            'enterprisePriceMinor' => $enterpriseTotal,
            'branchCount' => $branchCount,
            'canSubscribeEnterprise' => $plans->canSubscribeEnterprise($organization),
            'enterpriseMinBranches' => (int) config('care.enterprise.min_branches', 1),
            'prepaidMonths' => (array) config('care.prepaid_months', [6, 12, 24]),
            'currency' => (string) config('billing.currency', 'GHS'),
            'planExpiresAt' => $expiresAt,
            'billedBranches' => (int) ($settings['billed_branches'] ?? $branchCount),
            'salesUrl' => ladill_platform_url('contact-sales'),
        ]);
    }

    public function subscribe(Request $request, PlanService $plans, BillingClient $billing): RedirectResponse
    {
        $this->authorizeAbility($request, 'settings.manage');
        $organization = $this->organization($request);

        if ($plans->hasPaidPlan($organization)) {
            return redirect()->route('care.pro.index')
                ->with('success', 'Your organization already has an active paid plan.');
        }

        $validated = $request->validate([
            'branches' => ['required', 'integer', 'min:1', 'max:999'],
        ]);

        $branches = $plans->resolveCheckoutBranches($organization, (int) $validated['branches']);
        $amountMinor = $plans->priceForBranches('pro', $branches);

        return $this->chargeMonthlyWallet(
            $organization,
            $billing,
            $amountMinor,
            'pro',
            'care_pro',
            'care-pro-'.$organization->id.'-'.now()->format('Y-m-d-His'),
            'Ladill Care Pro — '.$branches.' branch(es) monthly',
            'Welcome to Care Pro — active for one month.',
            $branches,
        );
    }

    public function subscribeEnterprise(Request $request, PlanService $plans, BillingClient $billing): RedirectResponse
    {
        $this->authorizeAbility($request, 'settings.manage');
        $organization = $this->organization($request);

        if ($plans->hasPaidPlan($organization)) {
            return redirect()->route('care.pro.index')
                ->with('success', 'Your organization already has an active paid plan.');
        }

        if (! $plans->canSubscribeEnterprise($organization)) {
            $min = (int) config('care.enterprise.min_branches', 1);

            return redirect()->route('care.pro.index')
                ->with('error', "Enterprise requires at least {$min} active branch. Contact sales for custom multi-site onboarding.");
        }

        $validated = $request->validate([
            'branches' => ['required', 'integer', 'min:1', 'max:999'],
        ]);

        $branches = $plans->resolveCheckoutBranches($organization, (int) $validated['branches']);
        $amountMinor = $plans->priceForBranches('enterprise', $branches);

        return $this->chargeMonthlyWallet(
            $organization,
            $billing,
            $amountMinor,
            'enterprise',
            'care_enterprise',
            'care-enterprise-'.$organization->id.'-'.now()->format('Y-m-d-His'),
            'Ladill Care Enterprise — '.$branches.' branch(es) monthly',
            'Welcome to Care Enterprise — active for one month.',
            $branches,
        );
    }

    public function subscribePrepaid(Request $request, PlanService $plans, BillingClient $billing): RedirectResponse
    {
        $this->authorizeAbility($request, 'settings.manage');
        $validated = $request->validate([
            'plan' => ['required', 'in:pro,enterprise'],
            'months' => ['required', 'integer', 'in:6,12,24'],
            'branches' => ['required', 'integer', 'min:1', 'max:999'],
        ]);

        $organization = $this->organization($request);
        if ($plans->hasPaidPlan($organization)) {
            return redirect()->route('care.pro.index')
                ->with('success', 'Your organization already has an active paid plan.');
        }

        $plan = $validated['plan'];
        $months = (int) $validated['months'];

        if ($plan === 'enterprise' && ! $plans->canSubscribeEnterprise($organization)) {
            $min = (int) config('care.enterprise.min_branches', 1);

            return redirect()->route('care.pro.index')
                ->with('error', "Enterprise requires at least {$min} active branch.");
        }

        $branches = $plans->resolveCheckoutBranches($organization, (int) $validated['branches']);
        $monthlyMinor = $plans->priceForBranches($plan, $branches);
        $amountMinor = $monthlyMinor * $months;

        try {
            $checkout = $billing->initiatePlanCheckout(
                $organization->owner_ref,
                $plan,
                $months,
                $amountMinor,
                route('care.pro.paystack.callback'),
                [
                    'organization_id' => $organization->id,
                    'billed_branches' => $branches,
                ],
            );
        } catch (\Throwable) {
            return redirect()->route('care.pro.index')
                ->with('error', 'Could not start Paystack checkout. Please try again.');
        }

        $url = trim((string) ($checkout['checkout_url'] ?? ''));
        if ($url === '') {
            return redirect()->route('care.pro.index')
                ->with('error', 'Paystack did not return a checkout URL.');
        }

        return redirect()->away($url);
    }

    public function paystackCallback(Request $request, BillingClient $billing, PlanService $plans): RedirectResponse
    {
        $reference = (string) $request->query('reference', '');
        if ($reference === '') {
            return redirect()->route('care.pro.index')->with('error', 'Missing payment reference.');
        }

        try {
            $result = $billing->verifyPlanCheckout($reference);
        } catch (\Throwable) {
            return redirect()->route('care.pro.index')
                ->with('error', 'Could not verify payment. Contact support with reference: '.$reference);
        }

        if (! ($result['paid'] ?? false)) {
            return redirect()->route('care.pro.index')
                ->with('error', 'Payment was not completed.');
        }

        $metadata = (array) ($result['metadata'] ?? []);
        $organization = Organization::query()->find((int) ($metadata['organization_id'] ?? 0));
        if (! $organization) {
            return redirect()->route('care.pro.index')
                ->with('error', 'Organization not found for this payment.');
        }

        $this->authorizeAbility($request, 'settings.manage');
        if ($this->organization($request)->id !== $organization->id) {
            abort(403);
        }

        $plan = (string) ($result['plan'] ?? 'pro');
        $months = (int) ($result['months'] ?? 0);
        $branches = isset($metadata['billed_branches'])
            ? (int) $metadata['billed_branches']
            : max(1, $plans->activeBranchCount($organization));

        $this->activatePrepaidPlan($organization, $plan, $months, $branches);

        $label = $plan === 'enterprise' ? 'Care Enterprise' : 'Care Pro';

        return redirect()->route('care.pro.index')
            ->with('success', "{$label} is active for {$months} months.");
    }

    private function chargeMonthlyWallet(
        Organization $organization,
        BillingClient $billing,
        int $priceMinor,
        string $plan,
        string $billingSource,
        string $reference,
        string $description,
        string $successMessage,
        int $billedBranches,
    ): RedirectResponse {
        try {
            if (! $billing->canAfford($organization->owner_ref, $priceMinor)) {
                return redirect()->route('care.pro.index')
                    ->with('error', 'Insufficient wallet balance. Top up your Ladill wallet to upgrade.');
            }

            $charged = $billing->debit(
                $organization->owner_ref,
                $priceMinor,
                $billingSource,
                $reference,
                $description,
            );
        } catch (\Throwable) {
            return redirect()->route('care.pro.index')
                ->with('error', 'Could not process upgrade. Please try again.');
        }

        if (! $charged) {
            return redirect()->route('care.pro.index')
                ->with('error', 'Insufficient wallet balance. Top up your Ladill wallet to upgrade.');
        }

        $settings = $organization->settings ?? [];
        $settings['plan'] = $plan;
        $settings['auto_renew'] = true;
        $settings['billing_method'] = 'wallet_monthly';
        $settings['billed_branches'] = $billedBranches;
        $expires = now()->addDays((int) config('care.pro.period_days', 30));
        $settings['plan_expires_at'] = $expires->toIso8601String();
        unset($settings['plan_renewal_error'], $settings['enterprise_billed_branches']);
        $organization->update(['settings' => $settings]);

        $billing->syncSuiteEntitlement(
            $organization->owner_ref,
            $plan === 'enterprise' ? 'enterprise' : 'pro',
            'active',
            $reference,
            [
                'period_starts_at' => now()->toIso8601String(),
                'period_ends_at' => $expires->toIso8601String(),
                'source' => 'wallet_debit',
                'metadata' => ['billed_branches' => $billedBranches],
            ],
        );

        return redirect()->route('care.pro.index')->with('success', $successMessage);
    }

    private function activatePrepaidPlan(
        Organization $organization,
        string $plan,
        int $months,
        int $billedBranches,
    ): void {
        $settings = $organization->settings ?? [];
        $settings['plan'] = $plan;
        $settings['auto_renew'] = false;
        $settings['billing_method'] = 'paystack_prepaid';
        $settings['billed_branches'] = $billedBranches;
        $expires = now()->addMonths($months);
        $settings['plan_expires_at'] = $expires->toIso8601String();
        unset($settings['plan_renewal_error'], $settings['enterprise_billed_branches']);
        $organization->update(['settings' => $settings]);

        // Prepaid already writes entitlements on platform checkout; sync as repair.
        app(BillingClient::class)->syncSuiteEntitlement(
            $organization->owner_ref,
            $plan === 'enterprise' ? 'enterprise' : 'pro',
            'active',
            'care-prepaid-sync-'.$organization->id.'-'.now()->format('YmdHis'),
            [
                'period_starts_at' => now()->toIso8601String(),
                'period_ends_at' => $expires->toIso8601String(),
                'source' => 'checkout',
                'metadata' => ['billed_branches' => $billedBranches],
            ],
        );
    }
}
