<?php

namespace App\Http\Controllers\Store;

use App\Enums\AcceptanceContext;
use App\Enums\ContractType;
use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\Contract;
use App\Models\Order;
use App\Models\Reseller;
use App\Models\ResellerCommission;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class ResellerController extends Controller
{
    /**
     * Reseller dashboard with stats.
     */
    public function dashboard()
    {
        $reseller = $this->getReseller();

        if ($redirect = $this->ensureAgreementAccepted()) {
            return $redirect;
        }

        $stats = [
            'total_clients' => Client::where('reseller_id', $reseller->id)->count(),
            'total_orders' => Order::where('reseller_id', $reseller->id)->count(),
            'total_revenue' => Order::where('reseller_id', $reseller->id)
                ->where('payment_status', 'completed')
                ->sum('total'),
            'pending_commissions' => ResellerCommission::where('reseller_id', $reseller->id)
                ->pending()
                ->sum('commission_amount'),
            'total_commissions' => ResellerCommission::where('reseller_id', $reseller->id)
                ->sum('commission_amount'),
        ];

        $recentOrders = Order::where('reseller_id', $reseller->id)
            ->with('client')
            ->orderByDesc('created_at')
            ->limit(5)
            ->get();

        $recentClients = Client::where('reseller_id', $reseller->id)
            ->withCount('products')
            ->orderByDesc('created_at')
            ->limit(5)
            ->get();

        // PRC-845 — son 6 ay komisyon özeti (hafif; ay gruplaması PHP'de,
        // driver-agnostik — raw SQL tarih fonksiyonu yok). Net (negatif iade
        // düzeltmeleri dahil).
        $since = now()->startOfMonth()->subMonths(5);
        $byMonth = ResellerCommission::where('reseller_id', $reseller->id)
            ->where('created_at', '>=', $since)
            ->get(['commission_amount', 'created_at'])
            ->groupBy(fn ($c) => $c->created_at->format('Y-m'))
            ->map(fn ($g) => round((float) $g->sum('commission_amount'), 2));

        $monthlyCommissions = [];
        for ($i = 5; $i >= 0; $i--) {
            $month = now()->startOfMonth()->subMonths($i);
            $monthlyCommissions[] = [
                'label' => $month->format('M Y'),
                'total' => (float) ($byMonth[$month->format('Y-m')] ?? 0),
            ];
        }

        return view('clientarea.reseller.dashboard', [
            'reseller' => $reseller,
            'stats' => $stats,
            'recentOrders' => $recentOrders,
            'recentClients' => $recentClients,
            'monthlyCommissions' => $monthlyCommissions,
        ]);
    }

    /**
     * List reseller's clients.
     */
    public function clients()
    {
        $reseller = $this->getReseller();

        if ($redirect = $this->ensureAgreementAccepted()) {
            return $redirect;
        }

        $clients = Client::where('reseller_id', $reseller->id)
            ->withCount(['products', 'domains'])
            ->orderByDesc('created_at')
            ->paginate(20);

        return view('clientarea.reseller.clients', [
            'reseller' => $reseller,
            'clients' => $clients,
        ]);
    }

    /**
     * List orders from reseller's clients.
     */
    public function orders()
    {
        $reseller = $this->getReseller();

        if ($redirect = $this->ensureAgreementAccepted()) {
            return $redirect;
        }

        $orders = Order::where('reseller_id', $reseller->id)
            ->with('client')
            ->orderByDesc('created_at')
            ->paginate(20);

        return view('clientarea.reseller.orders', [
            'reseller' => $reseller,
            'orders' => $orders,
        ]);
    }

    /**
     * List reseller's commissions.
     */
    public function commissions()
    {
        $reseller = $this->getReseller();

        if ($redirect = $this->ensureAgreementAccepted()) {
            return $redirect;
        }

        $commissions = ResellerCommission::where('reseller_id', $reseller->id)
            ->with(['order', 'client'])
            ->orderByDesc('created_at')
            ->paginate(20);

        $totals = [
            'pending' => ResellerCommission::where('reseller_id', $reseller->id)->pending()->sum('commission_amount'),
            'approved' => ResellerCommission::where('reseller_id', $reseller->id)->approved()->sum('commission_amount'),
            'paid' => ResellerCommission::where('reseller_id', $reseller->id)->paid()->sum('commission_amount'),
        ];

        return view('clientarea.reseller.commissions', [
            'reseller' => $reseller,
            'commissions' => $commissions,
            'totals' => $totals,
        ]);
    }

    /**
     * Returns a redirect response if the active reseller_agreement contract
     * exists but the client hasn't yet accepted it. Returns null when the gate
     * passes (no contract, or already accepted).
     */
    protected function ensureAgreementAccepted(): ?Response
    {
        $client = Auth::guard('client')->user();
        if (! $client) {
            return null;
        }

        $contract = Contract::active()
            ->ofType(ContractType::RESELLER_AGREEMENT)
            ->ordered()
            ->first();
        if (! $contract) {
            return null; // No contract configured, no gate
        }

        $accepted = $client->contractAcceptances()
            ->where('contract_id', $contract->id)
            ->where('acceptance_context', AcceptanceContext::RESELLER_SIGNUP->value)
            ->exists();
        if ($accepted) {
            return null;
        }

        return redirect()->route('store.auth.reseller.agreement.show');
    }

    /**
     * Get active reseller or abort 403.
     */
    private function getReseller(): Reseller
    {
        $client = Auth::guard('client')->user();
        $reseller = $client->resellerProfile;

        if (! $reseller || $reseller->status !== 'active') {
            abort(403);
        }

        return $reseller;
    }
}
