<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once('_conf/globals.php');
require_once('_conf/db_con.php');


$postData = file_get_contents('php://input');
$postData = json_decode($postData);
$postAction = isset($postData->action) && !empty($postData->action) ? $postData->action : 'custom';
if($postAction == 'login'){
    $sql = $db_con->prepare('SELECT * FROM admins WHERE username = :username');
    $sql->bindValue(':username', $postData->userData->username);
    $sql->execute();
    $numRows =  $sql->rowCount();
    if($numRows){
        $user = $sql->fetch(PDO::FETCH_ASSOC);
        if(password_verify($postData->userData->password, $user['psw'])){
            $hex = bin2hex(random_bytes(36 / 2));
            $_SESSION['admin'] = true;
            $_SESSION['auth'] = $hex;
            $_SESSION['userid'] = $user['ID'];
            $response = new stdClass();
            $response->status = true;
            $sql = $db_con->prepare('UPDATE admins SET session_hex = :hex WHERE ID = :id');
            $sql->bindValue(':hex', $hex);
            $sql->bindValue(':id', $user['ID']);
            $sql->execute();
        }else{
            $response = new stdClass();
            $response->status = false;
        }
    }else{
        $response = new stdClass();
        $response->status = false;
    }
    echo json_encode($response);
}

if($postAction == 'isAuth'){
    if (session_status() === PHP_SESSION_ACTIVE) {
        $session_hex = isset($_SESSION['auth']) && !empty($_SESSION['auth']) ? $_SESSION['auth'] : '';
        $user_id = isset($_SESSION['userid']) && !empty($_SESSION['userid']) ? $_SESSION['userid'] : '';

        $sql = $db_con->prepare('SELECT * FROM admins WHERE ID = :id AND session_hex = :hex');
        $sql->bindValue(':id', $user_id);
        $sql->bindValue(':hex', $session_hex);
        $sql->execute();
        $rowC = $sql->rowCount();
        if($rowC){
            $response = new stdClass();
            $response->status = true;
        }else{
            session_destroy();
            $response = new stdClass();
            $response->status = false;
        }
        echo json_encode($response);
    }
}

function privAuth(){
    global $db_con;
    if (session_status() === PHP_SESSION_ACTIVE) {
        $session_hex = isset($_SESSION['auth']) && !empty($_SESSION['auth']) ? $_SESSION['auth'] : '';
        $user_id = isset($_SESSION['userid']) && !empty($_SESSION['userid']) ? $_SESSION['userid'] : '';

        $sql = $db_con->prepare('SELECT * FROM admins WHERE ID = :id AND session_hex = :hex');
        $sql->bindValue(':id', $user_id);
        $sql->bindValue(':hex', $session_hex);
        $sql->execute();
        $rowC = $sql->rowCount();
        if($rowC){
            return true;
        }else{
            session_destroy();
            return false;
        }
    }
}


if($postAction == 'logout'){
    if (session_status() === PHP_SESSION_ACTIVE) {
        $session_hex = isset($_SESSION['auth']) && !empty($_SESSION['auth']) ? $_SESSION['auth'] : '';
        $user_id = isset($_SESSION['userid']) && !empty($_SESSION['userid']) ? $_SESSION['userid'] : '';

        $sql = $db_con->prepare('UPDATE admins SET session_hex = "" WHERE ID = :id AND session_hex = :hex');
        $sql->bindValue(':id', $user_id);
        $sql->bindValue(':hex', '');
        $sql->execute();
        $rowC = $sql->rowCount();
        session_destroy();
    }
}

if($postAction == 'getUsers'){
    if(privAuth()){
        $sql = $db_con->prepare('SELECT * FROM users');
        $sql->execute();
        $_users = $sql->fetchAll(PDO::FETCH_ASSOC);
        $users = array();
        foreach($_users as $user){
            $_user = new stdClass();
            $_user->usid = isset($user['id']) && !empty($user['id']) ? $user['id'] : '';
            $_user->email = isset($user['u_email']) && !empty($user['u_email']) ? $user['u_email'] : '';
            $_user->username = isset($user['uname']) && !empty($user['uname']) ? $user['uname'] : '';
            $_user->regDate = isset($user['date_signed_up']) && !empty($user['date_signed_up']) ? $user['date_signed_up'] : '';
            $_user->stripe_cu = isset($user['stripe_cu']) && !empty($user['stripe_cu']) ? $user['stripe_cu'] : '';
            $users[] = $_user;
        }
        echo json_encode($users);
    }
}

if(isset($_POST['action']) && $_POST['action'] == 'insertUser'){
    $userData = json_decode($_POST['userData'], true);
    $username = isset($userData['username']) && !empty($userData['username']) ? $userData['username'] : '';
    $email = isset($userData['email']) && !empty($userData['email']) ? $userData['email'] : ''; 
    $password = isset($userData['password']) && !empty($userData['password']) ? $userData['password'] : '';
    $bio = isset($userData['bio']) && !empty($userData['bio']) ? $userData['bio'] : '';


    $pass = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

    if(isset($username) && !empty($username) && isset($email) && !empty($email) && isset($password) && !empty($password)){
        $sql = $db_con->prepare('INSERT INTO users (uname, psw, u_email, bio) VALUES (:uname, :psw, :email, :bio)');
        $sql->bindValue(':uname', $username);
        $sql->bindValue(':psw', $pass);
        $sql->bindValue(':email', $email);
        $sql->bindValue(':bio', $bio);
        $sql->execute();

        $rowC = $sql->rowCount();
        if($rowC > 0){
            $user_id = $db_con->lastInsertId();

            if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK){
                $avatar = $_FILES['avatar']['tmp_name'];
                $image_name = $_FILES['avatar']['name'];
                $image_size = $_FILES['avatar']['size'];
                $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
                $image_content = file_get_contents($avatar);

                $allowedPhotos = array('jpg', 'jpeg', 'png', 'gif');
                $name = generateRandomName();
                $name = $name . '.' . $ext;
                $path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';        
                if (in_array($ext, $allowedPhotos)) {
                    move_uploaded_file($avatar, $path . $name);
                }
        
                $stmt = $db_con->prepare('UPDATE users SET avatar = :avatar WHERE id = :id');
                $stmt->bindValue(':avatar', $name);
                $stmt->bindValue(':id', $user_id);
                $stmt->execute();
            }

            if(isset($_FILES['banner']) && $_FILES['banner']['error'] === UPLOAD_ERR_OK){
                $banner = $_FILES['banner']['tmp_name'];
                $image_name = $_FILES['banner']['name'];
                $image_size = $_FILES['banner']['size'];
                $ext = strtolower(pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION));
                $image_content = file_get_contents($banner);

                $allowedPhotos = array('jpg', 'jpeg', 'png', 'gif');
                $name = generateRandomName();
                $name = $name . '.' . $ext;
                $path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';        
                if (in_array($ext, $allowedPhotos)) {
                    move_uploaded_file($banner, $path . $name);
                }
        
                $stmt = $db_con->prepare('UPDATE users SET banner = :banner WHERE id = :id');
                $stmt->bindValue(':banner', $name);
                $stmt->bindValue(':id', $user_id);
                $stmt->execute();
            }

            foreach ($userData as $setting => $value) {
                if ($setting != 'username' || $setting != 'password' || $setting != 'email' || $setting != 'bio' || $setting != 'avatar' || $setting != 'banner') {
                    if (isset($value) && !empty($value)) {
                        update_user_data($setting, $value, $user_id);
                    }
                }
            }
        }
        

    }else{
        die();
    }
}

function generateRandomName($length = 32) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomName = '';
    $maxIndex = strlen($characters) - 1;
    
    for ($i = 0; $i < $length; $i++) {
        $randomName .= $characters[rand(0, $maxIndex)];
    }
    
    return $randomName;
}

function update_user_data($name, $value, $user){
    global $db_con;
    if(is_array($value)){
        $value = implode(",", $value);
    }
    $sql_con = $db_con->prepare('SELECT * FROM user_data WHERE data_name = :data_name AND user_id = :user_id');
    $sql_con->bindValue(':data_name', $name);
    $sql_con->bindValue(':user_id', $user);
    $sql_con->execute();

    $num_rows = $sql_con->rowCount();
    if($num_rows > 0){
        $sql_con = $db_con->prepare('UPDATE user_data SET data_value = :data_value WHERE user_id = :user_id AND data_name = :data_name');
        $sql_con->bindValue(':data_name', $name);
        $sql_con->bindValue(':data_value', $value);
        $sql_con->bindValue(':user_id', $user);
        $sql_con->execute();
    }else{
        $sql_con = $db_con->prepare('INSERT INTO user_data (data_name, data_value, user_id) VALUES (:data_name, :data_value, :user_id)');
        $sql_con->bindValue(':data_name', $name);
        $sql_con->bindValue(':data_value', $value);
        $sql_con->bindValue(':user_id', $user);
        $sql_con->execute();
    }
    // echo 'Executed ' . $name . ' with value ' . $value . '<br>';
}
?>