<?php

namespace App\Controllers;

use App\Models\AdminModel;
use App\Models\AktivitasModel;
use App\Models\PendidikanModel;

class Auth extends BaseController
{
    protected $adminModel;
    protected $aktivitasModel;
    protected $pendidikanModel;

    public function __construct()
    {
        $this->adminModel      = new AdminModel();
        $this->aktivitasModel  = new AktivitasModel();
        $this->pendidikanModel = new PendidikanModel();
        helper(['form', 'url']);
    }

    public function login()
    {
        if (session()->get('isLoggedIn')) {
            return redirect()->to('/auth/dashboard');
        }

        return view('auth/login');
    }

    public function attemptLogin()
    {
        $username = trim($this->request->getPost('username'));
        $password = $this->request->getPost('password');

        $admin = $this->adminModel->getAdmin($username);

        if (!$admin) {
            return redirect()->back()->with('error', 'Username / Email tidak ditemukan');
        }

        if (!password_verify($password, $admin['password'])) {
            return redirect()->back()->with('error', 'Password salah');
        }

        session()->regenerate(true);

        session()->set([
            'admin_id'       => $admin['id'],
            'admin_username' => $admin['username'],
            'isLoggedIn'      => true,
        ]);

        return redirect()->to('/auth/dashboard');
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }

    public function dashboard()
    {
        $data = [
            'totalAdmin'      => $this->adminModel->countAll(),
            'totalAktivitas'  => $this->aktivitasModel->countAll(),
            'totalPendidikan' => $this->pendidikanModel->countAll(),
        ];

        return view('auth/dashboard', $data);
    }

    public function index()
    {
        return view('auth/manage', [
            'admins' => $this->adminModel->findAll()
        ]);
    }

    public function create()
    {
        return view('auth/create');
    }

    public function store()
    {
        $rules = [
            'username' => 'required|min_length[3]|is_unique[admin.username]',
            'email'    => 'required|valid_email|is_unique[admin.email]',
            'password' => 'required|min_length[4]'
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('validation', $this->validator);
        }

        $this->adminModel->insert([
            'username' => $this->request->getPost('username'),
            'email'    => $this->request->getPost('email'),
            'password' => password_hash(
                $this->request->getPost('password'),
                PASSWORD_DEFAULT
            )
        ]);

        return redirect()->to('/auth')->with('success', 'Admin berhasil ditambahkan');
    }

    public function edit($id)
    {
        $admin = $this->adminModel->find($id);

        if (!$admin) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        return view('auth/edit', ['admin' => $admin]);
    }

    public function update($id)
    {
        $oldAdmin    = $this->adminModel->find($id);
        $newUsername = $this->request->getPost('username');
        $newEmail    = $this->request->getPost('email');

        $rules = [
            'username' => 'required|min_length[3]',
            'email'    => 'required|valid_email',
        ];

        if ($newUsername !== $oldAdmin['username']) {
            $rules['username'] .= '|is_unique[admin.username]';
        }

        if ($newEmail !== $oldAdmin['email']) {
            $rules['email'] .= '|is_unique[admin.email]';
        }

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('validation', $this->validator);
        }

        $data = [
            'username' => $newUsername,
            'email'    => $newEmail,
        ];

        if ($this->request->getPost('password')) {
            $data['password'] = password_hash(
                $this->request->getPost('password'),
                PASSWORD_DEFAULT
            );
        }

        $this->adminModel->update($id, $data);

        return redirect()->to('/auth')->with('success', 'Admin berhasil diupdate');
    }

    public function delete($id)
    {
        if ($id == session()->get('admin_id')) {
            return redirect()->to('/auth')
                ->with('error', 'Anda tidak bisa menghapus akun sendiri!');
        }

        $this->adminModel->delete($id);
        return redirect()->to('/auth')->with('success', 'Admin berhasil dihapus');
    }
}
