<?php
/**
 * File Name :			users.class.php
 * Class : 				Users
 * 		
 * This Class includes all the function which used in register,login
 * 
 */

class Users {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Check if user already exists
     */
    public function fetchUserExistOrNot($email)
    {
        $table = WP_PREFIX . "users";

        if (!empty($email)) {
            $email = strtolower($email);
            $sql = "SELECT COUNT(*) FROM $table WHERE user_email = :email";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute(['email' => $email]);
            $count = $stmt->fetchColumn();
            
            return $count > 0;
        }
        return false;
    }

	 /**
	 * Insert user registration data
	 */
	public function insertUser($data = [])
	{
		if (empty($data)) {
			return false;
		}

		$table = WP_PREFIX . "users";
		
		// Verify the group exists
		$stmt = $this->pdo->prepare("SELECT * FROM " . WP_PREFIX . "groups WHERE id = ?");
		$stmt->execute([$data['group_id']]);
		$group_details = $stmt->fetch(PDO::FETCH_ASSOC);
		
		if (!$group_details) {
			return false;
		}

		$regDate = date('Y-m-d H:i:s');
		$pass = trim($data['pass']);
		$salt = sha1(md5($pass));
		$newpassword = md5($pass . $salt);

		try {
			// Determine user type based on group name
			// $user_type = ($group_details['group_name'] === 'Demo') ? 'demo' : 'user';
			$user_type = ($data['group_id'] == 128) ? 'demo' : 'user';  // 128 is the demo group ID

			// Ensure email is lowercase
			$email = strtolower($data['email']);

			$sql = "INSERT INTO $table (user_email, user_pass, group_id, user_registered, user_status, user_type, user_group)
					VALUES (:email, :password, :group_id, :registered, '1', :user_type, (SELECT group_name FROM " . WP_PREFIX . "groups WHERE id = :group_id))";

			$stmt = $this->pdo->prepare($sql);
			$result = $stmt->execute([
				'email' => $email,
				'password' => $newpassword,
				'group_id' => $data['group_id'],
				'registered' => $regDate,
				'user_type' => $user_type
			]);

			if (!$result) {
				error_log("Error inserting user: " . print_r($stmt->errorInfo(), true));
				return false;
			}

			return $result;
		} catch (PDOException $e) {
			error_log("Exception inserting user: " . $e->getMessage());
			return false;
		}
	}



	
	/**
	 * function for login 
	 */
	public function doLogin($data)
    {
        if (empty($data)) {
            return false;
        }

        $pass = trim($data['pass']);
        $salt = sha1(md5($pass));
        $newpassword = md5($pass . $salt);

        // Ensure email is lowercase for login
        $email = strtolower($data['email']);

        $users = $this->getUsers($email, $newpassword);

        if (!empty($users)) {
            $_SESSION['front_user_email'] = $users[0]['user_email'];
            $_SESSION['front_user_id'] = $users[0]['ID'];
            $_SESSION['admin'] = $users[0]['is_admin'];
            $_SESSION['user_type'] = $users[0]['user_type']; 
            $_SESSION['user_group'] = $users[0]['user_group']; 

            // Redirect based on user type
            if ($users[0]['user_type'] === 'admin' || $users[0]['user_type'] === 'super') {
                // SWITCH CODE TO admin AFTER TESTING =========
				header('Location: ../../admin/');
				// ====== TEST - BYPASS ADMIN FOR THE MOMENT ========
                // header('Location: ../../');
                exit;
            }

            return true;
        } else {
            return false;
        }
    }
        
    /**
     * Function for get user by email
     */
	private function getUsers($email, $password)
	{
		$table = WP_PREFIX . "users";

		if (!empty($email)) {
			$email = strtolower($email);
			$sql = "SELECT u.*, g.group_name as user_group 
				   FROM $table u
				   LEFT JOIN wp_groups g ON u.group_id = g.id 
				   WHERE u.user_email = :email AND u.user_pass = :password AND u.user_status = '1'";
			$stmt = $this->pdo->prepare($sql);
			$stmt->execute(['email' => $email, 'password' => $password]);
			return $stmt->fetchAll(PDO::FETCH_ASSOC);
		}
		return false;
	}

        
    /**
    * function for get user by email 
    */
    public function getUsersFromId($id)
    {
        if (empty($id)) {
            return false;
        }

        $table = WP_PREFIX . "users";

        $sql = "SELECT * FROM $table WHERE ID = :id AND user_status = '1'";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['id' => $id]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $result ? $result : false;
    }

   /**
     * Function for get user by email and password
     */
    public function getUsersLogin($email, $password)
    {
        if (empty($email) || empty($password)) {
            return false;
        }

        $table = WP_PREFIX . "users";
        $email = strtolower($email);

        $sql = "SELECT * FROM $table WHERE user_email = :email AND user_pass = :password AND user_status = '1'";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['email' => $email, 'password' => $password]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $result ? $result : false;
    }
	
	/**
     * Check if user is logged in or not
     */
    public function checkUserLoginOrNot()
    {
        return isset($_SESSION['front_user_email']) && !empty($_SESSION['front_user_email']);
    }
	
	
	/**
         * insert userdata by id in groupsusers data 
         */
	public function insertUserData($data = array())
	{
		if (empty($data) || empty($data['user_id']) || empty($data['user_data'])) {
			echo "data not found";
			exit;
		}

		$table = WP_PREFIX . "groupusers_data";

		// Get user email
		$useremail_arr = $this->getUsersFromId($data['user_id']);
		if (empty($useremail_arr)) {
			echo "user not found";
			exit;
		}

		$user_email = $useremail_arr[0]['user_email'];

		// Extract grade and score from user_data
		preg_match('/Grade:\s*(.*?)\n/', $data['user_data'], $grade_matches);
		preg_match('/Score:\s*(.*?)\n/', $data['user_data'], $score_matches);

		$grade = isset($grade_matches[1]) ? trim($grade_matches[1]) : '';
		$score = isset($score_matches[1]) ? trim($score_matches[1]) : '';
		
		if ($grade === 'High') {
			$grade = 'High Pass';
		}

		// Insert data into table
		$sql = "INSERT INTO $table (user_id, user_data, case_grade, case_score) VALUES (:user_id, :user_data, :case_grade, :case_score)";
		$stmt = $this->pdo->prepare($sql);
		$result = $stmt->execute([
			'user_id' => $data['user_id'],
			'user_data' => $data['user_data']
		]);

		if (!$result) {
			// Get error info for debugging
			$errorInfo = $stmt->errorInfo();
			
			// Send error message to the browser console
			echo "<script>console.log('Data not added. Error: " . addslashes($errorInfo[2]) . "');</script>";
			exit;
		}

		// Email setup
		$xheaders = "From: Admin <noreply@anesoftcaselogs.com>\r\n";
		$xheaders .= "X-Sender: <noreply@anesoftcaselogs.com>\r\n";
		$xheaders .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";

		$message = "Case Log: <br/>";
		$message .= nl2br($data['user_data']);
		$message .= "<br/> End of Case Log.";

		// Send email
		mail($user_email, EMAIL_SUBJECT, $message, $xheaders);

		if ($result) {
			echo "data added successfully";
		} else {
			echo "data not added";
		}

		exit;
	}

        
       
}
?>
