<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Circle;
use App\Models\CircleMember;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Carbon\Carbon;

class AuthController extends Controller
{
    /**
     * Register / Login user
     * Developer phone verify karke yahan call karega
     * Agar user exist karta hai toh login, nahi toh register
     * Optional: circles bhi bhej sakta hai — register ke saath naye circles ban jayenge
     *
     * POST /api/auth/register
     * Body: { name, phone, fcm_token?, circles?: [{name: "Family"}, {name: "Friends"}] }
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'role' => 'required|string|in:parent,family_caregiver,partner,friend,other',
            'fcm_token' => 'nullable|string',
            'circles' => 'nullable|array|max:10',
            'circles.*.name' => 'required_with:circles|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors(),
            ], 422);
        }

        // Agar user already exist karta hai toh usse return karo with new token
        $user = User::where('phone', $request->phone)->first();

        if ($user) {
            // Update name & fcm_token if provided
            $user->update([
                'name' => $request->name,
                'role' => $request->role,
                'fcm_token' => $request->fcm_token,
            ]);
        } else {
            // Naya user banao
            $user = User::create([
                'name' => $request->name,
                'phone' => $request->phone,
                'role' => $request->role,
                'fcm_token' => $request->fcm_token,
            ]);
        }

        // Agar circles bhi bheje hain toh banao
        $createdCircles = [];
        if ($request->has('circles') && is_array($request->circles)) {
            foreach ($request->circles as $circleData) {
                $circle = Circle::create([
                    'name' => $circleData['name'],
                    'user_id' => $user->id,
                    'invite_code' => strtoupper(Str::random(3) . '-' . Str::random(3)),
                    'invite_code_expires_at' => Carbon::now()->addHours(24),
                ]);

                // Owner ko admin member banao
                CircleMember::create([
                    'circle_id' => $circle->id,
                    'user_id' => $user->id,
                    'role' => 'admin',
                ]);

                $circle->load(['owner:id,name,phone,avatar_url', 'members:id,name,phone,avatar_url']);
                $createdCircles[] = $circle;
            }
        }

        // Purane tokens delete karo
        $user->tokens()->delete();

        // Naya Sanctum token banao
        $token = $user->createToken('auth_token')->plainTextToken;

        $responseData = [
            'user' => $user,
            'token' => $token,
        ];

        // Agar circles banaye hain toh response mein bhi bhejo
        if (!empty($createdCircles)) {
            $responseData['circles'] = $createdCircles;
        }

        return response()->json([
            'success' => true,
            'message' => 'User registered successfully',
            'data' => $responseData,
        ], 201);
    }

    /**
     * Update FCM Token
     *
     * PUT /api/v1/auth/fcm-token
     * Body: { fcm_token }
     */
    public function updateFcmToken(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'fcm_token' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors(),
            ], 422);
        }

        $request->user()->update([
            'fcm_token' => $request->fcm_token,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'FCM token updated successfully',
        ]);
    }

    /**
     * Get current user profile
     * Token se user ki detail nikal ke return karta hai
     *
     * GET /api/v1/auth/me
     */
    public function me(Request $request)
    {
        $user = $request->user()->load('latestLocation');

        // Current token ki info
        $tokenInfo = $request->user()->currentAccessToken();

        return response()->json([
            'success' => true,
            'data' => [
                'user' => $user,
                'token_info' => [
                    'token_id' => $tokenInfo->id,
                    'token_name' => $tokenInfo->name,
                    'last_used_at' => $tokenInfo->last_used_at,
                    'created_at' => $tokenInfo->created_at,
                ],
            ],
        ]);
    }

    /**
     * Update profile
     *
     * PUT /api/v1/auth/profile
     * Body: { name?, avatar_url? }
     */
    public function updateProfile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'avatar_url' => 'sometimes|nullable|string|url',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validator->errors(),
            ], 422);
        }

        $request->user()->update($request->only(['name', 'avatar_url']));

        return response()->json([
            'success' => true,
            'message' => 'Profile updated successfully',
            'data' => $request->user(),
        ]);
    }

    /**
     * Logout - delete current token
     *
     * POST /api/v1/auth/logout
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully',
        ]);
    }
}
