<?php

namespace App\Http\Controllers;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (Auth::guard('web')->check()) {
            return redirect('/');
        }
        return view('auth.login');
    }

    public function showRegister()
    {
        if (Auth::guard('web')->check()) {
            return redirect('/');
        }
        return view('auth.register');
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $credentials = $request->only('email', 'password');

        if (Auth::guard('web')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended('/')->with('success', 'Welcome back, ' . Auth::guard('web')->user()->name . '!');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->withInput();
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'phone' => 'required|string|max:20',
            'verification_code' => 'required|string|size:6',
            'password' => 'required|string|min:6|confirmed',
            'terms' => 'required|accepted',
        ], [
            'verification_code.required' => 'Kode verifikasi harus diisi',
            'verification_code.size' => 'Kode verifikasi harus 6 digit',
            'terms.required' => 'You must agree to the Terms & Conditions.',
            'terms.accepted' => 'You must agree to the Terms & Conditions.',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // Verify code again before registration
        $verification = DB::table('email_verification_codes')
            ->where('email', $request->email)
            ->where('code', $request->verification_code)
            ->first();

        if (!$verification || Carbon::parse($verification->expires_at)->isPast()) {
            return back()->withErrors(['verification_code' => 'Kode verifikasi tidak valid atau expired'])->withInput();
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'email_verified_at' => now(),  // Mark as verified since they verified via code
        ]);

        // Delete verification code
        DB::table('email_verification_codes')
            ->where('email', $request->email)
            ->delete();

        Auth::guard('web')->login($user);
        $request->session()->regenerate();

        return redirect('/')->with('success', 'Selamat datang di RISTOPUP, ' . $user->name . '!');
    }

    public function logout(Request $request)
    {
        Auth::guard('web')->logout();

        // Only regenerate token, don't invalidate entire session
        // This preserves other guard sessions (like admin)
        $request->session()->regenerateToken();

        return redirect()->route('login')->with('success', 'You have been logged out successfully.');
    }

    public function sendVerificationCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => 'Email tidak valid'], 422);
        }

        $email = $request->email;

        // Check if email already registered
        if (User::where('email', $email)->exists()) {
            return response()->json(['message' => 'Email sudah terdaftar'], 422);
        }

        // Generate 6 digit code
        $code = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $expiresAt = Carbon::now()->addMinutes(5);

        // Delete old codes for this email
        DB::table('email_verification_codes')
            ->where('email', $email)
            ->delete();

        // Save new code
        DB::table('email_verification_codes')->insert([
            'email' => $email,
            'code' => $code,
            'expires_at' => $expiresAt,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // Send email
        try {
            Mail::send('emails.verification-code', ['code' => $code], function ($message) use ($email) {
                $message
                    ->to($email)
                    ->subject('Kode Verifikasi - RISTOPUP');
            });

            return response()->json([
                'message' => 'Kode verifikasi telah dikirim ke email Anda',
                'success' => true
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Gagal mengirim email: ' . $e->getMessage()], 500);
        }
    }

    public function verifyCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'code' => 'required|string|size:6',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => 'Data tidak valid'], 422);
        }

        $verification = DB::table('email_verification_codes')
            ->where('email', $request->email)
            ->where('code', $request->code)
            ->first();

        if (!$verification) {
            return response()->json(['message' => 'Kode verifikasi salah'], 422);
        }

        // Check if expired
        if (Carbon::parse($verification->expires_at)->isPast()) {
            return response()->json(['message' => 'Kode verifikasi expired'], 422);
        }

        return response()->json([
            'message' => 'Email berhasil diverifikasi',
            'success' => true
        ]);
    }
}
