<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use CodeIgniter\Config\Config;
use CodeIgniter\Database\Query;
use CodeIgniter\API\ResponseTrait;

class Login extends BaseController
{
    var $model, $validation;
    use ResponseTrait;
    function __construct()
    {
        $this->model = new AdminModel();
        $this->validation = \Config\Services::validation();
        helper("cookie");
        helper("global_fungsi_helper");
    }

    public function getIndex()
    {
        if (session()->has('admin_username')) {
            return redirect()->to('admin/dashboard');
        }
        return view('admin/auth/login');
    }

    public function postLogin()
    {
        $rules = [
            'username' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Username harus diisi',
                ],
            ],
            'password' => [
                'rules' => 'required',
                'errors' => [
                    'required' => 'Password harus diisi',
                ],
            ],
        ];

        if (!$this->validate($rules)) {
            session()->setFlashdata('warning', $this->validator->getErrors());
            return redirect()->back()->withInput();
        }

        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');
        $remember = $this->request->getVar('remember_me');


        $admin = $this->model->getData($username);

        if (!$admin || !password_verify($password, $admin['password'])) {
            session()->setFlashdata('warning', ['Username atau password salah.']);
            return redirect()->back()->withInput();
        }

        // Set remember me token
        if ($remember == '1') {
            $token = bin2hex(random_bytes(32));
            set_cookie('admin_remember_token', $token, 3600 * 24 * 30);
            $this->model->update($admin['id'], ['remember_token' => hash('sha256', $token)]);
        }


        $sessionData = [
            'admin_id' => $admin['id'],
            'admin_username' => $admin['username'],
            'admin_email' => $admin['email'],
            'admin_role' => $admin['role'],
            'admin_picture' => $admin['picture'],
        ];

        session()->set($sessionData);

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

    function getLogout()
    {
        // delete_cookie("admin_cookie_username");
        // delete_cookie("admin_cookie_password");
        session()->destroy();
        if (session()->get('admin_username') != '') {
            session()->setFlashdata("success", "Anda berhasil logout");
        }
        echo view("admin/auth/login");
    }

    function postLupapassword()
    {
        $err = [];
        if ($this->request->getMethod() == 'post') {
            $username = $this->request->getVar('username');
            if ($username == '') {
                $err[] = "Silakan masukkan username atau email yang anda punya";
            }
            if (empty($err)) {
                $data = $this->model->getData($username);
                if (empty($data)) {
                    $err[] = "Akun yang kamu masukkan tidak terdata";
                }
            }
            if (empty($err)) {
                $email = $data['email'];
                $token = md5(date('ymdhis'));

                $link = site_url("admin/resetpassword/?email=$email&token=$token");
                $attachment = "";
                $to = $email;
                $title = "Reset Password";
                $message = "Berikut ini adalah link untuk melakukan reset password Anda.";
                $message .= "Silakan klik link berikut ini $link";

                // kirim_email($attachment, $to, $title, $message);

                $dataUpdate = [
                    'email' => $email,
                    'token' => $token
                ];
                $this->model->updateData($dataUpdate);
                session()->setFlashdata("success", "Email untuk recovery sudah kami kirimkan ke email anda");
            }
            if ($err) {
                session()->setFlashdata("username", $username);
                session()->setFlashdata("warning", $err);
            }
            return redirect()->to("admin/lupapassword");
        }
        echo view("admin/auth/forgot_password");
    }
}
