<?php
namespace WpBookingProFrontend\app\models;
defined('_WPBOOKINGPRO_EXEC') or die;

use Exception;
use WpBookingPro\Factory;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingPro\Utilities\Utility;

class LoginModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "login";
    /**
     * @var string
     */
    public $table_name = "user";

    public function programmaticLogin($data = array()) {
        add_action('init',array($this,'logout_before_login'));
        $email_or_username = isset($data['email_or_username'])? sanitize_text_field($data['email_or_username']) : '';
        $password = isset($data['password']) ? sanitize_text_field($data['password']) : '';
        $remember_login = isset($data['remember_login']) ? (bool)$data['remember_login'] : false;
        if(!function_exists('wp_get_current_user')) {
            include(ABSPATH . "wp-includes/pluggable.php");
        }
        if (filter_var($email_or_username, FILTER_VALIDATE_EMAIL)) { //Invalid Email
            $user = get_user_by('email', $email_or_username);
        } else {
            $user = get_user_by('login', $email_or_username );
        }

        if($user && wp_check_password( $password, $user->data->user_pass, $user->ID)) {
            $creds = array('user_login' => $user->data->user_login, 'user_password' => $password);
            $user_login = wp_signon( $creds);
            $_SESSION['user_id'] = $user_login->ID;
            $_SESSION['user_login'] = $user_login->data->user_login;
            $_SESSION['remember'] = $remember_login;
            return $user_login;
        }
        return false;
        
    }
    function logout_before_login() {
        if ( is_user_logged_in() ) {
            wp_logout();
        }
    }




}
