<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    /**
     * Accepts email + password (admin / traditional accounts) or phone + password
     * (legacy clients: users.email stores E.164, PIN = password).
     *
     * Also accepts a single "credential" field (email or phone) to avoid stale clients
     * sending empty email with phone and failing validation.
     */
    public function login(Request $request)
    {
        $this->normalizeLoginPayload($request);

        $request->validate([
            'password' => 'required|string',
            'email' => 'required_without:phone|nullable|email',
            'phone' => 'required_without:email|nullable|string',
        ]);

        if (filled($request->email)) {
            $identifier = strtolower(trim((string) $request->email));
            $user = User::whereRaw('LOWER(email) = ?', [$identifier])->first();
        } else {
            $e164 = $this->normalizePhoneToE164((string) $request->phone);
            $user = null;
            if ($e164 !== '') {
                $user = User::where('email', $e164)->orWhere('phone', $e164)->first();
            }
        }

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Teléfono o contraseña incorrectos.'], 401);
        }

        if (! $user->is_active) {
            return response()->json(['message' => 'Cuenta inactiva.'], 403);
        }

        $token = $user->createToken('api-token')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'role' => $user->role,
            ],
        ]);
    }

    /**
     * Flattens credential / clears empty strings so Laravel validation and branches behave.
     */
    private function normalizeLoginPayload(Request $request): void
    {
        $credential = $request->input('credential');
        if (is_string($credential) && trim($credential) !== '') {
            $credential = trim($credential);
            if (str_contains($credential, '@')) {
                $request->merge(['email' => $credential, 'phone' => null]);
            } else {
                $request->merge(['phone' => $credential, 'email' => null]);
            }
        }

        if ($request->input('email') === '' || $request->input('email') === null) {
            $request->merge(['email' => null]);
        }
        if ($request->input('phone') === '' || $request->input('phone') === null) {
            $request->merge(['phone' => null]);
        }
    }

    /**
     * Maps common CR phone input to E.164 stored in users.email for phone-based accounts.
     */
    private function normalizePhoneToE164(string $input): string
    {
        $raw = preg_replace('/\D/', '', $input) ?? '';

        if ($raw === '') {
            return '';
        }

        if (str_starts_with($raw, '506') && strlen($raw) > 8) {
            return '+'.$raw;
        }

        return '+506'.$raw;
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out']);
    }

    public function me(Request $request)
    {
        return response()->json($request->user());
    }

    public function changePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'new_password' => 'required|string|min:6|confirmed',
        ]);

        $user = $request->user();

        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json(['message' => 'Current password is incorrect'], 400);
        }

        $user->update([
            'password' => Hash::make($request->new_password)
        ]);

        return response()->json(['message' => 'Password changed successfully']);
    }

    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:6|confirmed',
            'phone' => 'nullable|string|max:20',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phone' => $request->phone,
            'role' => 'client',
            'is_active' => true,
        ]);

        $token = $user->createToken('api-token')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
            ],
        ], 201);
    }
}
