<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Models\Users;
use App\Mail\VerificationCodeMail;
use Carbon\Carbon;

class AuthenController extends Controller
{
    /**
     * Tampilkan form login
     */
    public function showLogin()
    {
        return view('authen.login');
    }

    /**
     * Proses login
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            $user = Auth::user();
            
            // Cek apakah email sudah diverifikasi
            if (!$user->is_verified) {
                Auth::logout();
                return redirect()->route('verify.show', ['email' => $user->email])
                    ->withErrors(['email' => 'Silakan verifikasi email Anda terlebih dahulu.']);
            }

            if ($user->role === 'admin') {
                return redirect()->route('dashboard');
            }

            if ($user->role === 'pengguna') {
                return redirect()->route('product.index');
            }

            abort(403, 'Role tidak dikenali.');
        }

        return back()->withErrors([
            'email' => 'Email atau password salah!',
        ])->onlyInput('email');
    }

    /**
     * TAMPILKAN FORM REGISTER
     */
    public function showRegister()
    {
        return view('authen.register');
    }

    /**
     * Proses register dengan verifikasi email
     */
    public function register(Request $request)
    {
        // Validasi dengan nama tabel yang benar: tbl_users
        $request->validate([
            'username' => 'required|unique:tbl_users,username',
            'email' => 'required|email|unique:tbl_users,email',
            'password' => 'required|confirmed|min:6',
        ]);

        // Generate kode verifikasi 6 digit
        $verificationCode = rand(100000, 999999);
        
        // Set expiry 15 menit dari sekarang
        $expiry = Carbon::now()->addMinutes(15);

        try {
            // Buat user baru
            $user = Users::create([
                'username' => $request->username,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'role' => 'pengguna',
                'verification_code' => $verificationCode,
                'verification_expiry' => $expiry,
                'is_verified' => false
            ]);

            // Kirim email verifikasi
            try {
                Mail::to($user->email)->send(new VerificationCodeMail($verificationCode, $user->username));
                $message = 'Kode verifikasi telah dikirim ke email Anda.';
            } catch (\Exception $e) {
                \Log::error('Gagal kirim email verifikasi: ' . $e->getMessage());
                $message = 'Registrasi berhasil! (Email tidak terkirim) Kode verifikasi: ' . $verificationCode;
            }

            // Redirect ke halaman verifikasi
            return redirect()->route('verify.show', ['email' => $user->email])
                ->with('success', $message);

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Registrasi gagal: ' . $e->getMessage()])->withInput();
        }
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }

    /**
     * Tampilkan form verifikasi
     */
    public function showVerifyForm($email)
    {
        // Cek apakah user ada di tabel tbl_users
        $user = Users::where('email', $email)->first();
        
        if (!$user) {
            return redirect()->route('register')
                ->withErrors(['email' => 'Email tidak ditemukan. Silakan registrasi ulang.']);
        }
        
        // Cek apakah sudah terverifikasi
        if ($user->is_verified) {
            return redirect()->route('login')
                ->with('success', 'Email sudah terverifikasi. Silakan login.');
        }
        
        return view('authen.verify', compact('email'));
    }

    /**
     * Verifikasi kode
     */
    public function verifyCode(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'code' => 'required|numeric|digits:6'
        ]);

        $user = Users::where('email', $request->email)->first();

        if (!$user) {
            return back()->withErrors(['email' => 'Email tidak ditemukan.']);
        }

        // Cek apakah sudah terverifikasi
        if ($user->is_verified) {
            return redirect()->route('login')
                ->with('info', 'Email Anda sudah terverifikasi. Silakan login.');
        }

        // Cek kode verifikasi
        if ($user->verification_code != $request->code) {
            return back()->withErrors(['code' => 'Kode verifikasi tidak valid.']);
        }

        // Cek expiry - Convert ke Carbon
        $expiry = Carbon::parse($user->verification_expiry);
            
        if (Carbon::now()->gt($expiry)) {
            return back()->withErrors(['code' => 'Kode verifikasi sudah kadaluarsa. Silakan minta kode baru.']);
        }

        // Update status verifikasi
        $user->update([
            'is_verified' => true,
            'verification_code' => null,
            'verification_expiry' => null
        ]);

        return redirect()->route('login')
            ->with('success', 'Email berhasil diverifikasi! Silakan login untuk memulai.');
    }

    /**
     * Kirim ulang kode
     */
    public function resendCode(Request $request)
    {
        $request->validate([
            'email' => 'required|email'
        ]);

        $user = Users::where('email', $request->email)->first();

        if (!$user) {
            return back()->withErrors(['email' => 'Email tidak ditemukan.']);
        }

        // Cek apakah sudah terverifikasi
        if ($user->is_verified) {
            return redirect()->route('login')
                ->with('success', 'Email sudah terverifikasi. Silakan login.');
        }

        // Generate kode baru
        $newCode = rand(100000, 999999);
        $newExpiry = Carbon::now()->addMinutes(15);
        
        $user->update([
            'verification_code' => $newCode,
            'verification_expiry' => $newExpiry
        ]);

        // Kirim ulang email
        try {
            Mail::to($user->email)->send(new VerificationCodeMail($newCode, $user->username));
            return back()->with('success', 'Kode verifikasi baru telah dikirim ke email Anda.');
        } catch (\Exception $e) {
            \Log::error('Gagal kirim ulang email: ' . $e->getMessage());
            return back()->with('warning', 'Gagal mengirim email. Kode verifikasi Anda: ' . $newCode);
        }
    }

    /**
     * Debug: Cek status verifikasi
     */
    public function debugStatus($email)
    {
        $user = Users::where('email', $email)->first();
        
        if (!$user) {
            return response()->json(['error' => 'User tidak ditemukan'], 404);
        }
        
        return response()->json([
            'user_id' => $user->user_id,
            'username' => $user->username,
            'email' => $user->email,
            'is_verified' => $user->is_verified,
            'verification_code' => $user->verification_code,
            'verification_expiry' => $user->verification_expiry ? Carbon::parse($user->verification_expiry)->format('Y-m-d H:i:s') : null,
            'server_time' => Carbon::now()->format('Y-m-d H:i:s'),
            'expiry_status' => $user->verification_expiry ? 
                (Carbon::now()->gt(Carbon::parse($user->verification_expiry)) ? 'Expired' : 'Valid') : 'No expiry'
        ]);
    }
}