<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Mail\SendOtpMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class AuthController extends Controller
{
    // --- FUNGSI REGISTRASI ---
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'address' => 'required|string',
            'phone_number' => 'required|string',
        ]);

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

        $user->profile()->create([
            'address' => $request->address,
            'phone_number' => $request->phone_number,
        ]);

        $otp = rand(100000, 999999);
        $user->otp_code = $otp;
        $user->otp_expires_at = Carbon::now()->addMinutes(10);
        $user->save();

        Mail::to($user->email)->send(new SendOtpMail($otp));

        return response()->json(['message' => 'Registrasi berhasil. Silakan cek email untuk kode OTP.'], 201);
    }

    // --- FUNGSI VERIFIKASI OTP ---
    public function verifyOtp(Request $request)
    {
        $request->validate(['email' => 'required|email|exists:users,email', 'otp' => 'required|numeric']);
        
        $user = User::where('email', $request->email)->first();

        if (!$user || $user->otp_code != $request->otp) {
            return response()->json(['message' => 'Kode OTP tidak valid.'], 400);
        }
        if (Carbon::now()->isAfter($user->otp_expires_at)) {
            return response()->json(['message' => 'Kode OTP sudah kedaluwarsa.'], 400);
        }

        $user->email_verified_at = Carbon::now();
        $user->otp_code = null;
        $user->otp_expires_at = null;
        $user->save();
        
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'message' => 'Akun berhasil diverifikasi!',
            'access_token' => $token,
            'token_type' => 'Bearer',
        ]);
    }
    
    // --- FUNGSI LOGIN ---
    public function login(Request $request)
    {
        $request->validate(['email' => 'required|email', 'password' => 'required|string']);

        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['message' => 'Email atau password salah.'], 401);
        }

        $user = User::where('email', $request->email)->firstOrFail();

        if (!$user->email_verified_at) {
            // Jika mau, Anda bisa membuat logika kirim ulang OTP di sini
            return response()->json(['message' => 'Akun belum diverifikasi.'], 403);
        }

        $token = $user->createToken('auth_token')->plainTextToken;
        return response()->json([
            'message' => 'Login berhasil!',
            'access_token' => $token,
            'user' => $user->load('profile')
        ]);
    }
    
    // --- FUNGSI LOGOUT ---
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logout berhasil.']);
    }
}