<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UserModel;
use App\Models\KeanggotaanModel;

class LoginController extends Controller
{
    public function index(Request $request)
    {
        if ($request->session()->get('role') === 'Administrator') {
            return redirect('/dashboard/beranda');
        }
        return view("login");
    }
    public function submitForm(Request $request)
    {
        $validated = $request->validate([
            'username' => 'required',
            'password' => 'required|min:6'
        ]);

        $data = [
            "username" => $request->request->get('username'),
            "password" => md5($request->request->get('password')),
            "status" => "Aktif"
        ];
        $result = UserModel::checkLogin($data);
        if ($result->status() === 400) {
            return redirect('login')->with('response', ['status' => 400, 'message' => "Username atau password salah, atau pengguna tidak aktif!"]);
        } else {
            $request->session()->put('role', $result->getData()->data->role);
            $request->session()->put('userID', $result->getData()->data->id);
            $request->session()->put('name', $result->getData()->data->name);
            $request->session()->put('foto', $result->getData()->data->foto);
        }
        if ($result->getData()->data->role === "Administrator") {
            return redirect('dashboard/beranda');
        } else {
            return redirect('dashboard/biodata');
        }
    }
    public function logout(Request $request)
    {
        $request->session()->forget('role');
        return redirect('login')->with('response', ['status' => 200, 'message' => "Anda telah berhasil logout!"]);
    }

    public function cek_anggota(Request $request)
    {
        $anggotaID = $request->input('kode_anggota');
        $anggota = KeanggotaanModel::where('kode_anggota', $anggotaID)->first();

        if ($anggota) {
            if ($anggota->status === 'Disetujui') {
                return response()->json(['status' => 200, 'message' => 'Anggota aktif', 'anggota' => [
                    'username' => strtolower(str_replace(' ', '', $anggota->nama_perusahaan)),
                    'password' => $anggota->password_default,
                ]]);
            } else if ($anggota->status === 'Ditolak') {
                return response()->json(['status' => 400, 'message' => 'Anggota tidak aktif', 'keterangan' => $anggota->keterangan]);
            } else {
                return response()->json(['status' => 401, 'message' => 'Dalam proses pengajuan']);
            }
        } else {
            return response()->json(['status' => 404, 'message' => 'Anggota tidak ditemukan']);
        }
    }
}
