<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    // --- Menampilkan Form ---
    public function showRegisterForm()
    {
        return view('auth.register');
    }

    public function showLoginForm()
    {
        return view('auth.login');
    }

    // --- Memproses Form Register ---
   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',
            'dusun' => 'required|string',
            'address' => 'required|string',
            'phone_number' => 'required|string',
            'ktp' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'foto' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'latitude' => 'required|string',
            'longitude' => 'required|string',
        ]);

        // Upload file KTP
        $ktpPath = $request->file('ktp')->store('ktp', 'public');
        
        // Upload file Foto
        $fotoPath = $request->file('foto')->store('foto_pendaftaran', 'public');

        // Gabung dusun + alamat
        $fullAddress = $request->dusun . ', ' . $request->address;

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

        $user->profile()->create([
            'address' => $fullAddress,
            'phone_number' => $request->phone_number,
            'ktp' => $ktpPath,
            'foto' => $fotoPath,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
        ]);

        return redirect()->route('login')->with('status', 'Pendaftaran berhasil. Akun Anda menunggu verifikasi admin.');
    }

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

    if (Auth::attempt($credentials)) {
        $user = Auth::user();

        // Cek status user
        if ($user->status !== 'aktif') {
            Auth::logout();

            // Pesan sesuai status
            switch ($user->status) {
                case 'pending':
                    $message = '⏳ Akun Anda masih menunggu verifikasi admin.';
                    break;
                case 'disetujui':
                    $message = '✅ Akun Anda sudah disetujui! Menunggu petugas memasang meteran. Silakan tunggu.';
                    break;
                case 'nonaktif':
                    $message = '🚫 Akun Anda telah dinonaktifkan. Silakan hubungi admin.';
                    break;
                case 'ditolak':
                    $message = '❌ Pendaftaran Anda ditolak. Silakan hubungi admin untuk informasi lebih lanjut.';
                    break;
                default:
                    $message = '⚠ Status akun tidak dikenali. Silakan hubungi admin.';
            }

            return back()->with('error', $message);
        }

        // Status aktif, login berhasil!
        $request->session()->regenerate();
        return redirect()->intended('home');
    }

    return back()->with('error', 'Email atau password salah.');
    }
    // --- Proses Logout ---
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/login');
    }
}