<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreBusinessRequest;
use App\Models\Business;
use Illuminate\Http\JsonResponse;

/**
 * Manages tenant (Business) records. These endpoints intentionally bypass
 * the BelongsToBusiness scope (Business itself isn't scoped to a business),
 * so route access here should be restricted to admin/owner roles at the
 * route middleware or policy level — this controller does not enforce that.
 */
class BusinessController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        if ($user && $user->is_super_admin) {
            $businesses = Business::query()->latest()->paginate(25);
        } else {
            $businesses = Business::where('owner_id', $user->id)
                ->orWhere('id', $user->business_id)
                ->latest()
                ->paginate(25);
        }

        return view('businesses.index', compact('businesses'));
    }

    public function create()
    {
        return view('businesses.create');
    }

    public function store(\App\Http\Requests\StoreBusinessRequest $request): JsonResponse
    {
        $user = auth()->user();
        if ($user && $user->business_id) {
            $userBusiness = Business::find($user->business_id);
            if ($userBusiness) {
                $currentLocationsCount = Business::where('owner_id', $user->id)->count();
                if (!$userBusiness->checkLimit('max_locations', $currentLocationsCount)) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Business locations limit reached for your subscription plan.'
                    ], 422);
                }
            }
        }

        $data = $request->validated();
        $logo = $request->file('invoice_logo');
        $template = $request->input('invoice_layout_template', 'classic');

        unset($data['invoice_logo'], $data['invoice_layout_template']);

        if ($user) {
            $data['owner_id'] = $user->id;
        }

        $business = Business::create($data);

        if ($user && empty($user->business_id)) {
            $user->business_id = $business->id;
            $user->save();
        }

        if ($logo) {
            $path = $logo->store('logos', 'public');
            \App\Models\Setting::set('invoice_logo_url', '/storage/' . $path, $business->id);
        }

        if ($template) {
            \App\Models\Setting::set('invoice_layout_template', $template, $business->id);
        }

        return response()->json(['success' => true, 'data' => $business], 201);
    }

    public function show(Business $business)
    {
        $this->authorizeBusinessAccess($business);
        return view('businesses.show', compact('business'));
    }

    public function edit(Business $business)
    {
        $this->authorizeBusinessAccess($business);
        $logoUrl = \App\Models\Setting::get('invoice_logo_url', '', $business->id);
        $layoutTemplate = \App\Models\Setting::get('invoice_layout_template', 'classic', $business->id);
        return view('businesses.edit', compact('business', 'logoUrl', 'layoutTemplate'));
    }

    public function update(StoreBusinessRequest $request, Business $business): JsonResponse
    {
        $this->authorizeBusinessAccess($business);
        $data = $request->validated();
        $logo = $request->file('invoice_logo');
        $template = $request->input('invoice_layout_template');

        unset($data['invoice_logo'], $data['invoice_layout_template']);

        if (empty($data['sandbox_token'])) {
            unset($data['sandbox_token']);
        }
        if (empty($data['production_token'])) {
            unset($data['production_token']);
        }

        $business->update($data);

        if ($logo) {
            $path = $logo->store('logos', 'public');
            \App\Models\Setting::set('invoice_logo_url', '/storage/' . $path, $business->id);
        }

        if ($template) {
            \App\Models\Setting::set('invoice_layout_template', $template, $business->id);
        }

        return response()->json(['success' => true, 'data' => $business->fresh()]);
    }

    public function destroy(Business $business): JsonResponse
    {
        $this->authorizeBusinessAccess($business);
        $business->delete();

        return response()->json(['success' => true]);
    }

    /**
     * Quick connectivity check — verifies the configured token actually
     * works against FBR by hitting a lightweight reference endpoint.
     */
    public function testConnection(Business $business, \App\Services\FbrDigitalInvoiceService $fbr): JsonResponse
    {
        $this->authorizeBusinessAccess($business);
        try {
            $fbr->forBusiness($business)->getProvinces();

            return response()->json([
                'success' => true,
                'message' => 'Connection successful — token is valid for ' . ($business->is_sandbox ? 'sandbox' : 'production') . '.',
            ]);
        } catch (\App\Exceptions\FbrApiException $e) {
            return $e->render();
        }
    }

    /**
     * Authorize access to a specific business.
     */
    protected function authorizeBusinessAccess(Business $business): void
    {
        $user = auth()->user();
        if ($user && $user->is_super_admin) {
            return;
        }

        if (!$user || ($business->id !== $user->business_id && $business->owner_id !== $user->id)) {
            abort(403, 'Unauthorized access to this business.');
        }
    }
}
