<?php
require_once 'db_functions.php';
require_once 'article_functions.php';

use Postmark\PostmarkClient;

function user_id_exists($user_id)
{
    $result = exec_stmt('SELECT user_id FROM user WHERE user_id = ?', 'i', $user_id)->fetch_assoc();

    if ($result == null)
        return false;
    return true;
}

function username_exists($username) {}

function cookies($user, $time)
{
    setcookie('user_id', $user['user_id'], $time);
    setcookie('username', $user['username'], $time);
    setcookie('email', $user['email'], $time);
    setcookie('role_id', $user['role_id'], $time);
    setcookie('profile_picture', $user['profile_picture'], $time);
}

function logout()
{
    foreach (array_keys($_COOKIE) as $key) {
        setcookie($key, '', time() - 3600, '/');
        unset($_COOKIE[$key]);
    }

    foreach (array_keys($_SESSION) as $key) {
        unset($_SESSION[$key]);
    }

    header('Location: articles.php');
}

function login_form($error_msg = '')
{
    $form = '
        <div class="form_card">
            <h3 class="underline">Log In</h3>
            <form method="post">
                <input type="hidden" name="form_id" value="login_form">

                <label for="username">Username / Email</label>
                <input id="username" name="username" required>

                <label for="password">Password</label>
                <input id="password" name="password" type="password" required>

                <label class="form_checkbox_container">Stay Logged In?
                    <input name="stay_logged_in" type="checkbox" value="true">
                    <span class="checkmark"></span>
                </label>

                <input class="button" type="submit" value="Log In">
                ' . $error_msg . '
            </form>
        </div>
    ';

    return $form;
}

function login($username, $password, $stay_logged_in)
{
    $password_hash = hash('sha256', $password);

    $user = exec_stmt('SELECT user_id, username, email, role_id, profile_picture FROM user WHERE username = ? OR email = ? AND password_hash = ?', 'sss', $username, $username, $password_hash)->fetch_assoc();

    if ($user == null) {
        $error_msg = '
            <div class="error">
                Username and/or Password are invalid!
            </div>
        ';

        return $error_msg;
    }

    $time = time() + 60 * 60 * 1;
    cookies($user, $time);

    if ($stay_logged_in) {
        $token = bin2hex(random_bytes(64));
        // echo $token . '<br>';
        // echo strlen($token);
        setcookie('remember_user', $token, time() + 60 * 60 * 24 * 30, '/', '', true, true);

        exec_stmt('INSERT INTO remember_user (token, user_id, remote_addr, http_forward) VALUES (?, ?, ?, ?)', 'siss', $token, $user['user_id'], hash('sha256', $_SERVER['REMOTE_ADDR']), (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? hash('sha256', $_SERVER['HTTP_X_FORWARDED_FOR']) : null));
    }

    return true;
}

function signup_form($error_msg = '')
{
    $form = '
        <div class="form_card">
            <h3 class="underline">Sign Up</h3>
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="form_id" value="signup_form">
                <input type="hidden" name="crop_x" value="" id="crop_x">
                <input type="hidden" name="crop_y" value="" id="crop_y">
                <input type="hidden" name="crop_width" value="" id="crop_width">
                <input name="required_field" id="required_field" value="">

                <label for="username">Username</label>
                <input id="username" name="username" required>

                <label for="email">Email Address</label>
                <input id="email" name="email" required>

                <label for="password">Password</label>
                <input id="password" name="password" type="password" required>

                <label for="verify_password">Verify Password</label>
                <input id="verify_password" name="verify_password" type="password" required>

                <label for="profile_picture_input" class="upload_button modal_button" id="profile_cropper_button">Upload a Profile Picture</label>
                <input id="profile_picture_input" class="file_input" name="profile_picture" type="file" accept="image/png, image/jpeg, image/jpg">
                <small class="file_input_feedback">No file selected.</small>

                <label class="form_checkbox_container">Stay Logged In?
                    <input name="stay_logged_in" type="checkbox" value="true">
                    <span class="checkmark"></span>
                </label>

                <input class="button" type="submit" value="Sign Up">
                ' . $error_msg . '
            </form>

            <div id="modal" class="modal">
                <div id="display_modal"></div>
            </div>

            <div style="display: none;">
                <div id="profile_cropper" class="modal_form">' . profile_cropper() . '</div>
            </div>
        </div>
    ';

    return $form;
}

function create_user($username, $email, $password, $verify_password, $role_id, $upload = null, $x = null, $y = null, $crop_width = null, $honeypot = null)
{
    if (!empty($honeypot)) {
        $error_msg = '
            <div class="error">
                You are a bot. Leave now.
            </div>
        ';

        return $error_msg;
    }

    if ($password != $verify_password) {
        $error_msg = '
            <div class="error">
                Passwords do not match!
            </div>
        ';

        return $error_msg;
    }

    if (username_exists($username)) {
        $error_msg = '
            <div class="error">
                Username is taken!
            </div>
        ';
    }

    $password_hash = hash('sha256', $password);

    $id = rand(1000, 999999999);
    while (user_id_exists($id))
        $id = rand(1000, 999999999);

    if (!empty($upload['profile_picture']['tmp_name'])) {
        $orig_size = getimagesize($upload['profile_picture']['tmp_name']);
        $orig_width = $orig_size[0];
        $orig_height = $orig_size[1];

        $crop_size = min($orig_width, $orig_height) * 0.56;

        crop_image($upload['profile_picture']['tmp_name'], $x, $y, $crop_size, $crop_size);
        $target = upload($upload['profile_picture'], $_ENV['PROFILE_IMAGES_FQ_PATH'], $id);
    } else {
        $target = 'default-profile.png';
    }

    exec_stmt('INSERT INTO user (user_id, username, email, password_hash, role_id, profile_picture) VALUES (?, ?, ?, ?, ?, ?)', 'isssis', $id, $username, $email, $password_hash, $role_id, $target);
    return true;
}

function profile_cropper()
{
    $display = '
        <div class="form_card">
            <img src="IMG_UPLOAD_PATH" id="img_to_crop"/>
            <div id="img_crop_selection">
                <div class="corner" id="corner_nw"></div>
                <div class="corner" id="corner_ne"></div>
                <div class="corner" id="corner_sw"></div>
                <div class="corner" id="corner_se"></div>
            </div>

            <div class="row">
                <button id="crop_button" class="button">Crop</button>
                <button id="crop_cancel" class="button">Cancel</button>
            </div>
        </div>
    ';

    return $display;
}

function reset_pw_form()
{
    $form = '
        <div class="form_card">
            <h5 class="underline">Reset Password</h5>
            <span class="modal_close">&times;</span>
            <form method="post">
                <input type="hidden" name="form_id" value="reset_pw_form">
                <input type="hidden" name="user_id" value="' . $_GET['user_id'] . '">

                <label for="new_pw">New Password</label>
                <input id="new_pw" name="new_pw" type="password" required>

                <label for="verify_new_pw">Verify New Password</label>
                <input id="verify_new_pw" name="verify_new_pw" type="password" required>
            
                <input type="submit" class="button" value="Reset Password">
            </form>
        </div>
    ';

    return $form;
}

function reset_password($user_id, $new_password, $verify_new_password)
{
    if ($new_password != $verify_new_password) {
        $error_msg = '
            <div class="error">
                Passwords do not match!
            </div>
        ';

        return $error_msg;
    }

    $password_hash = hash('sha256', $new_password);
    exec_stmt('UPDATE user SET password_hash = ? WHERE user_id = ?', 'si', $password_hash, $user_id);
}

function update_email_form()
{
    $form = '
        <div class="form_card">
            <h5 class="underline">Update Email</h5>
            <span class="modal_close">&times;</span>
            <form method="post">
                <input type="hidden" name="form_id" value="update_email_form">
                <input type="hidden" name="user_id" value="' . $_GET['user_id'] . '">

                <label for="new_email">New Email</label>
                <input id="new_email" name="new_email" required>

                <label for="verify_new_email">Verify New Email</label>
                <input id="verify_new_email" name="verify_new_email" required>
            
                <input type="submit" class="button" value="Update Email">
            </form>
        </div>
    ';

    return $form;
}

function update_email($user_id, $new_email, $verify_new_email)
{
    if ($new_email != $verify_new_email) {
        $error_msg = '
            <div class="error">
                Emails do not match!
            </div>
        ';

        return $error_msg;
    }

    exec_stmt('UPDATE user SET email = ? WHERE user_id = ?', 'si', $new_email, $user_id);
}

function update_username_form()
{
    $form = '
        <div class="form_card">
            <h5 class="underline">Update Username</h5>
            <span class="modal_close">&times;</span>
            <form method="post">
                <input type="hidden" name="form_id" value="update_username_form">
                <input type="hidden" name="user_id" value="' . $_GET['user_id'] . '">

                <label for="new_username">New Username</label>
                <input id="new_username" name="new_username" required>

                <label for="verify_new_username">Verify New Username</label>
                <input id="verify_new_username" name="verify_new_username" required>
            
                <input type="submit" class="button" value="Update Username">
            </form>
        </div>
    ';

    return $form;
}

function update_username($user_id, $new_username, $verify_new_username)
{
    if ($new_username != $verify_new_username) {
        $error_msg = '
            <div class="error">
                Usernames do not match!
            </div>
        ';

        return $error_msg;
    }

    if ($result = username_exists($new_username))
        return $result;

    exec_stmt('UPDATE user SET username = ? WHERE user_id = ?', 'si', $new_username, $user_id);
}

function update_profile_picture_form()
{
    $form = '
        <div class="form_card">
            <h5 class="underline">Update Profile Picture</h5>
            <span class="modal_close">&times;</span>
            <form method="post">
                <input type="hidden" name="form_id" value="update_profile_picture_form">
                <input type="hidden" name="user_id" value="' . $_GET['user_id'] . '">
                <input type="hidden" name="crop_x" value="" id="crop_x">
                <input type="hidden" name="crop_y" value="" id="crop_y">
                <input type="hidden" name="crop_width" value="" id="crop_width">

                <label for="profile_picture_input" class="upload_button modal_button" id="profile_cropper_button">Upload a Profile Picture</label>
                <input id="profile_picture_input" class="file_input" name="profile_picture" type="file" accept="image/png, image/jpeg, image/jpg">
                <small class="file_input_feedback">No file selected.</small>
            
                <input type="submit" class="button" value="Update Profile Picture">
            </form>

            <div id="modal" class="modal">
                <div id="display_modal"></div>
            </div>

            <div style="display: none;">
                <div id="profile_cropper" class="modal_form">' . profile_cropper() . '</div>
            </div>
        </div>
    ';

    return $form;
}

function update_profile_picture($user_id) {}

function request_role_change_form()
{
    $conn = get_connection();
    $result = $conn->query('SELECT * FROM roles WHERE role_id <> 1');

    $roles = '<div class="checkboxes">';
    while ($row = $result->fetch_assoc()) {
        $roles .= '
            <label class="form_checkbox_container">' . $row['role'] . '
                <input name="requested_role" value="' . $row['role_id'] . '" type="radio"' . ($row['role_id'] == $_COOKIE['role_id'] ? ' checked' : '') . '>
                <span class="checkmark"></span>
            </label>
        ';
    }

    $roles .= '</div>';

    $form = '
        <div class="form_card">
            <h5 class="underline">Request Role</h5>
            <span class="modal_close">&times;</span>
            <form method="post">
                <input type="hidden" name="form_id" value="request_role_change_form">
                ' . $roles . '
            
                <input type="submit" class="button" value="Request Role">
            </form>
        </div>
    ';

    return $form;
}

function request_role_change($user_id, $new_role_id)
{
    $user = exec_stmt('SELECT user_id, username, email, roles.role, created_at FROM user INNER JOIN roles WHERE user.role_id = roles.role_id AND user_id = ?', 'i', $user_id)->fetch_assoc();
    $new_role = exec_stmt('SELECT role FROM roles WHERE role_id = ?', 'i', $new_role_id)->fetch_array();

    $email_html = '
        <h1>User Role Change Request</h1>
        <p>The following user has requested their role on vintagecoding.net to be changed:</p>
        <p><strong>User ID: </strong>' . $user['user_id'] . '</p>
        <p><strong>Username: </strong>' . $user['username'] . '</p>
        <p><strong>Email: </strong>' . $user['email'] . '</p>
        <p><strong>Current Role: </strong>' . $user['role'] . ' -> ' . $new_role[0] . '</p>
        <p><strong>Created At: </strong>' . $user['created_at'] . '</p>
    ';

    $client = new PostmarkClient($_ENV['POSTMARK_API_TOKEN']);

    $client->sendEmail(
        'mailer@joshashton.dev',
        'me@joshashton.dev',
        'User Role Change Request - ' . $user['user_id'],
        $email_html
    );
}

function delete_account_form()
{
    $form = '
        <div class="form_card">
            <h5 class="underline">Delete Account</h5>
            <span class="modal_close">&times;</span>
            <form method="post">
                <input type="hidden" name="form_id" value="delete_account_form">
                <input type="hidden" name="user_id" value="' . $_GET['user_id'] . '">

                <label for="delete_password">Password</label>
                <input id="delete_password" name="delete_password" type="password" required>

                <label for="delete_verify_password">Verify Password</label>
                <input id="delete_verify_password" name="delete_verify_password" type="password" required>
            
                <input type="submit" class="button" value="Delete Account">
            </form>
        </div>
    ';

    return $form;
}

function delete_account($user_id, $password = null, $verify_password = null)
{
    if ($user_id == 2025) {
        $error_msg = '
            <div class="error">
                I am the owner, and I cannot delete myself...
            </div>
        ';

        return $error_msg;
    }

    if ($password != $verify_password) {
        $error_msg = '
            <div class="error">
                Passwords do not match!
            </div>
        ';

        return $error_msg;
    }

    if ($password && $verify_password) {
        $password_hash = hash('sha256', $password);
        $user = exec_stmt('SELECT user_id, profile_picture FROM user WHERE user_id = ? AND password_hash = ?', 'is', $user_id, $password_hash)->fetch_assoc();

        if ($user == null) {
            $error_msg = '
                <div class="error">
                    Username and/or Password are invalid!
                </div>
            ';

            return $error_msg;
        }

        // Hardcoded prevention of deleting the owner's profile picture
        if (!empty($user['profile_picture']) && $user['profile_picture'] != '2025.jpg')
            delete_file($_ENV['PROFILE_IMAGES_FQ_PATH'] . $user['profile_picture']);

        exec_stmt('DELETE FROM user WHERE user_id = ?', 'i', $user_id);
        logout();
    } else if ($_COOKIE['role_id'] <= 2) {
        $user = exec_stmt('SELECT user_id, profile_picture FROM user WHERE user_id = ?', 'i', $user_id)->fetch_assoc();

        if ($user['user_id'] == 2025) {
            $error_msg = '
                <div class="error">
                    Cannot delete the owner!
                </div>
            ';

            return $error_msg;
        }

        // Hardcoded prevention of deleting the owner's profile picture
        if (!empty($user['profile_picture']) && $user['profile_picture'] != '2025.jpg')
            delete_file($_ENV['PROFILE_IMAGES_FQ_PATH'] . $user['profile_picture']);

        exec_stmt('DELETE FROM user WHERE user_id = ?', 'i', $user_id);
    }
}

function user_view($user_id)
{
    $user = exec_stmt('SELECT user_id, username, email, role_id, created_at, last_active, is_active, profile_picture FROM user WHERE user_id = ?', 'i', $user_id)->fetch_assoc();
    if ($user == null)
        header('Location: articles.php');

    $view = '
    <div class="user_view">
        <div class="row">
            <h1>' . $user['username'] . '</h1>
            <div class="card_pic_box">
                <img src="' . $_ENV['PROFILE_IMAGES_PQ_PATH'] . $user['profile_picture'] . '" class="profile_picture" />
            </div>
        </div>
        <div class="line"></div>
    ';

    // TODO: Allow user to update profile picture.
    // <button id="update_profile_picture_form_button" class="modal_button underline">Update Profile Picture</button>
    // <div id="update_profile_picture_form" class="modal_form">' . update_profile_picture_form() . '</div>
    if ((isset($_COOKIE['user_id']) && $_COOKIE['user_id'] == $user_id) || (isset($_COOKIE['role_id']) && $_COOKIE['role_id'] <= 2)) {
        $view .= '
            <h3>User Actions</h3>
            <div class="user_actions">
                <button id="reset_pw_form_button" class="modal_button underline">Reset Password</button>
                <button id="update_email_form_button" class="modal_button underline">Update Email</button>
                <button id="update_username_form_button" class="modal_button underline">Update Username</button>
                <button id="request_role_form_button" class="modal_button underline">Request Role</button>
                <button id="delete_account_form_button" class="modal_button underline">Delete Account</button>
            </div>

            <div id="user_actions_modal" class="modal">
                <div id="modal_content"></div>
            </div>

            <div style="display: none;">
                <div id="reset_pw_form" class="modal_form">' . reset_pw_form() . '</div>
                <div id="update_email_form" class="modal_form">' . update_email_form() . '</div>
                <div id="update_username_form" class="modal_form">' . update_username_form() . '</div>
                <div id="request_role_change_form" class="modal_form">' . request_role_change_form() . '</div>
                <div id="delete_account_form" class="modal_form">' . delete_account_form() . '</div>
            </div>
        </div>
        ';
    } else {
        $ids = articles_ids_by_author($_GET['user_id']);
        $view .= '
            <div class="article_cards">
        ';

        foreach ($ids as $id)
            $view .= article_card($id);

        $view .= '</div>';
    }

    return $view;
}
