<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Anggota;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Mail\AnggotaBaruMenungguPersetujuan;
use Illuminate\Support\Facades\Storage;

class UserMemberController extends Controller
{

    public function create()
    {
        return view('user.member.create');
    }

    
    public function store(Request $request)
    {
        $request->validate([
            'nama'    => 'required|string|max:255',
            'nip_nim' => 'required|string|max:255|unique:anggota,nip_nim',
            'email'   => 'required|email|unique:anggota,email',
            'alamat'  => 'required|string',
            'no_hp'   => 'nullable|string|max:20',
            'foto'    => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        if (Auth::user()->anggota) {
            return redirect()->route('user.peminjaman.create')
                ->with('info', 'Kamu sudah terdaftar sebagai anggota.');
        }

        $namaFoto = null;

        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $namaFoto = time() . '_' . $file->getClientOriginalName();

            $folderPath = storage_path('app/public/foto_anggota');
            if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }

            $file->move($folderPath, $namaFoto);

            if (!file_exists($folderPath . '/' . $namaFoto)) {
                return back()->with('error', 'Foto gagal diupload.');
            }
        }

        $anggota = Anggota::create([
            'nama'    => $request->nama,
            'nip_nim' => $request->nip_nim,
            'email'   => $request->email,
            'alamat'  => $request->alamat,
            'no_hp'   => $request->no_hp ?? null,
            'user_id' => Auth::id(),
            'status'  => 'menunggu',
            'foto'    => $namaFoto,
        ]);

        try {
            Mail::to('admin@bakorwil.com')->send(new AnggotaBaruMenungguPersetujuan($anggota));
        } catch (\Exception $e) {
            \Log::error('Gagal mengirim email ke admin: ' . $e->getMessage());
        }

        Auth::user()->setRelation('anggota', $anggota);

        return redirect()->route('user.peminjaman.create')
            ->with('success', 'Data anggota berhasil dikirim. Mohon tunggu persetujuan admin.');
    }

   
    public function index()
    {
        $anggota = Anggota::latest()->take(5)->get();
        return view('user.member.index', compact('anggota'));
    }

    
    public function all()
    {
        $anggota = Anggota::latest()->get();
        return view('user.member.all', compact('anggota'));
    }

    
    public static function getFotoUrl($anggota)
    {
        if ($anggota->foto && file_exists(storage_path('app/public/foto_anggota/'.$anggota->foto))) {
            return asset('storage/foto_anggota/'.$anggota->foto);
        }
        return asset('images/default-user.png');
    }
}
