<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\User;
use App\Services\CompanyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Str;

class CompanyProfileController extends Controller
{
    public function __construct(
        private readonly CompanyService $companyService
    ) {}

    /**
     * Return the full profile for a company.
     *
     * Accessible by:
     *   - Admin (auth:sanctum)   — any company
     *   - Company admin (auth:portal_api) — their own company only
     *
     * Excluded from response: encrypted NIN/BVN fields, nin_photo (too large for list).
     */
    public function show(Request $request, Company $company): JsonResponse
    {
        try {
            // Portal users may only see their own company
            if (!($request->user() instanceof User)) {
                $portalUser = $request->user();
                if ((int) $portalUser->company_id !== (int) $company->id) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Unauthorized.',
                    ], 403);
                }
            }

            $profile         = $this->companyService->getFullCompanyProfile($company);
            $admins          = $profile['admins'];
            $stats           = $profile['stats'];
            $recentEmployees = $profile['recentEmployees'];

            return response()->json([
                'success' => true,
                'data'    => [
                    // ── Company ──────────────────────────────────────────────
                    'id'                => $company->id,
                    'name'              => $company->name,
                    'email'             => $company->email,
                    'phone'             => $company->phone,
                    'rc_number'         => $company->rc_number,
                    'address'           => $company->address,
                    'city'              => $company->city,
                    'state'             => $company->state,
                    'country'           => $company->country,
                    'insurance_type'    => $company->insurance_type,
                    'registration_date' => $company->registration_date,
                    'license_number'    => $company->license_number,
                    'status'            => $company->status,
                    'created_at'        => $company->created_at->toIso8601String(),
                    'updated_at'        => $company->updated_at->toIso8601String(),

                    // ── Admins ───────────────────────────────────────────────
                    'admins' => $admins->map(fn ($u) => [
                        'id'                 => $u->id,
                        'name'               => $u->name,
                        'email'              => $u->email,
                        'password_set'       => $u->hasSetPassword(),
                        'invitation_sent_at' => $u->invitation_sent_at?->toIso8601String(),
                        'two_factor_enabled' => $u->two_factor_enabled,
                        'created_at'         => $u->created_at->toIso8601String(),
                    ]),

                    // ── Employee stats (counts only) ─────────────────────────
                    'employee_stats' => $stats,

                    // ── Recent employees (last 10) ───────────────────────────
                    'recent_employees' => $recentEmployees->map(fn ($e) => [
                        'id'        => $e->id,
                        'name'      => $e->full_name,
                        'email'     => $e->email,
                        'position'  => $e->position,
                        'joined_at' => ($e->hire_date ?? $e->created_at)->toDateString(),
                    ]),
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching full company profile: ' . $e->getMessage(), [
                'company_id' => $company->id,
                'exception'  => $e,
            ]);
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching the company profile.',
            ], 500);
        }
    }

    /**
     * Generate (or regenerate) a registration link token for a company.
     *
     * Accessible by:
     *   - Admin (auth:sanctum)        — any company, requires generate_company_registration_link permission
     *   - Company admin (portal_api)  — their own company only
     */
    public function generateRegistrationLink(Request $request, Company $company): JsonResponse
    {
        $user = $request->user();

        if ($user instanceof User) {
            // System admin — check permission
            if ($user->cannot('generate_company_registration_link')) {
                return response()->json(['success' => false, 'message' => 'Unauthorized.'], 403);
            }
        } else {
            // Portal user — must be company_admin for this company
            if ($user->role !== 'company_admin' || (int) $user->company_id !== (int) $company->id) {
                return response()->json(['success' => false, 'message' => 'Unauthorized.'], 403);
            }
        }

        try {
            $token = Str::random(64);
            $company->update(['registration_token' => $token]);

            return response()->json([
                'success' => true,
                'message' => 'Registration link generated successfully.',
                'data' => [
                    'company_id'         => $company->id,
                    'company_name'       => $company->name,
                    'registration_token' => $token,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error generating company registration link: ' . $e->getMessage(), [
                'company_id' => $company->id,
                'exception'  => $e,
            ]);
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while generating the registration link.',
                'error'   => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }
}
