<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\Alumni;
use App\Models\ProfilJurusan;

class AlumniAuthController extends Controller
{
    /**
     * Show the alumni login form.
     */
    public function showLoginForm()
    {
        return view('auth.alumni');
    }

    /**
     * Handle alumni login attempt.
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        if (Auth::guard('alumni')->attempt($credentials, $request->boolean('remember'))) {
            $request->session()->regenerate();
            return redirect()->intended('/alumni/dashboard')
                ->with('success', 'Selamat datang kembali di Portal Alumni!');
        }

        return back()->withErrors([
            'username' => 'Username atau password Alumni salah.',
        ])->onlyInput('username');
    }

    /**
     * Handle alumni registration attempt.
     */
    public function register(Request $request)
    {
        $data = $request->validate([
            'nama' => 'required|string|max:200',
            'username' => 'required|string|max:100|unique:alumni,username',
            'password' => 'required|string|min:6',
            'tahun_lulus' => 'required|integer|min:1900|max:'.(date('Y') + 1),
            'kelanjutan' => 'required|in:kerja,kuliah',
            'tempat' => 'required|string|max:150',
            'jabatan' => 'required|string|max:100',
            'testimoni' => 'required|string',
        ]);

        // Fetch first available profile
        $profil = ProfilJurusan::first();
        $profilId = $profil ? $profil->id_profil : 1;

        $alumni = Alumni::create([
            'id_profil' => $profilId,
            'nama' => $data['nama'],
            'username' => $data['username'],
            'password' => Hash::make($data['password']),
            'tahun_lulus' => $data['tahun_lulus'],
            'kelanjutan' => $data['kelanjutan'],
            'tempat' => $data['tempat'],
            'jabatan' => $data['jabatan'],
            'testimoni' => $data['testimoni'],
            'foto' => 'default_alumni.jpg',
        ]);

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

        return redirect('/alumni/dashboard')
            ->with('success', 'Pendaftaran berhasil! Anda telah masuk ke Portal Alumni.');
    }

    /**
     * Log the alumni out.
     */
    public function logout(Request $request)
    {
        Auth::guard('alumni')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/')
            ->with('success', 'Anda telah berhasil logout dari portal Alumni.');
    }

    /**
     * Update current Alumni's own profile.
     */
    public function updateProfile(Request $request)
    {
        $alumni = Auth::guard('alumni')->user();

        $request->validate([
            'nama' => 'required|string|max:200',
            'username' => 'required|string|max:100|unique:alumni,username,' . $alumni->id_alumni . ',id_alumni',
            'password' => 'nullable|string|min:6',
            'tahun_lulus' => 'required|integer|min:1900|max:' . (date('Y') + 1),
            'kelanjutan' => 'required|in:kerja,kuliah',
            'tempat' => 'required|string|max:150',
            'jabatan' => 'required|string|max:100',
            'testimoni' => 'required|string',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = $alumni->foto;
        if ($request->hasFile('foto')) {
            if ($alumni->foto && $alumni->foto !== 'default_alumni.jpg' && file_exists(public_path($alumni->foto))) {
                @unlink(public_path($alumni->foto));
            }

            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/alumni'), $filename);
            $fotoPath = 'uploads/alumni/' . $filename;
        }

        $updateData = [
            'nama' => $request->nama,
            'username' => $request->username,
            'tahun_lulus' => $request->tahun_lulus,
            'kelanjutan' => $request->kelanjutan,
            'tempat' => $request->tempat,
            'jabatan' => $request->jabatan,
            'testimoni' => $request->testimoni,
            'foto' => $fotoPath,
        ];

        if ($request->filled('password')) {
            $updateData['password'] = Hash::make($request->password);
        }

        // Eloquent update
        Alumni::where('id_alumni', $alumni->id_alumni)->update($updateData);

        return redirect()->route('alumni.dashboard')->with('success', 'Profil Anda berhasil diperbarui!');
    }
}
