<?php

require_once APP_DIR . 'libs/View.php';

require_once APP_DIR . 'libs/Input.php';

require_once APP_DIR . 'libs/Session.php';

require_once APP_DIR . 'models/AuthModel.php';

class AuthController

{
    private $_view;
    private $_db;


    public function __construct()

    {
        check_login();

        $this->_view = new View();

        $this->_db = new Database();
    }


    public function index()
    {

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            $data = Input::filter_param($_POST);
            if (!(isset($data['username']) && !empty($data['username']) == true)) {
                set_session_alert('error', 'Please Enter User Name!');
                redirect(ADMIN_URL . 'login');
            }

            if (!(isset($data['password']) && !empty($data['password']) == true)) {
                set_session_alert('error', 'Please Enter Password!');
                redirect(ADMIN_URL . 'login');
            }

            $authObj = new AuthModel();
            $authObj->_set_colum = "id, username,screen_name, email, user_type, password, phone, upload_date";
            $u_exist = $authObj->checkUser('user', $data['username']);
            if (empty($u_exist)) {
                set_session_alert('error', 'Login Details Not found!');
                redirect(ADMIN_URL . 'login');
            } else {
                $u_fetch = $u_exist;
                $check_password = password_verify($data['password'], $u_fetch['password']);
                $authObj->resetColum();
                $authObj->resetPk();
                if (!$check_password) {
                    set_session_alert('error', 'Wrong Password, Please Try Again Later');
                    redirect(ADMIN_URL . 'login');
                } else {
                    SESSION::put('login', true);
                    SESSION::put('uId', $u_fetch['id']);
                    SESSION::put('uName', $u_fetch['username']);
                    SESSION::put('sName', $u_fetch['screen_name']);
                    set_session_alert('success', 'Login Successful!');
                    redirect(ADMIN_URL);
                }
            }
        } else {
            set_session_alert('error', 'Invalid Data');
            redirect(ADMIN_URL . 'login');
        }
    }
}
