<?php
require_once 'functions/init.php';

require_once 'functions/functions.php';
include_once 'functions/account_functions.php';

$msg = '';

if (isset($_POST['form_id'])) {
    switch ($_POST['form_id']) {
        case 'signup_form':
            $msg = signup(
                $_POST['username'],
                $_POST['email'],
                $_POST['password'],
                $_POST['verify_password'],
                4, // TODO: Need to allow for other roles to be created, if the submission is from an administrator or owner.
                (!empty($_FILES) ? $_FILES : ''),
                (!empty($_POST['crop_x']) ? $_POST['crop_x'] : ''),
                (!empty($_POST['crop_y']) ? $_POST['crop_y'] : ''),
                (!empty($_POST['crop_width']) ? $_POST['crop_width'] : '')
            );

            if ($msg === true)
                header('Location: user.php?action=view&user_id=' . $_COOKIE['user_id']);
            break;



        case 'login_form':
            $msg = login(
                $_POST['username'],
                $_POST['password'],
                (isset($POST['stay_logged_in']) ? true : false)
            );

            if ($msg === true)
                header('Location: .');
            break;



        case 'reset_pw_form':
            $msg = reset_password(
                ($_COOKIE['role_id'] <= 2 && $_COOKIE['user_id'] != $_POST['user_id'] ? $_POST['user_id'] : $_COOKIE['user_id']),
                $_POST['new_pw'],
                $_POST['verify_new_pw']
            );

            break;



        case 'update_email_form':
            $msg = update_email(
                ($_COOKIE['role_id'] <= 2 && $_COOKIE['user_id'] != $_POST['user_id'] ? $_POST['user_id'] : $_COOKIE['user_id']),
                $_POST['new_email'],
                $_POST['verify_new_email']
            );

            break;



        case 'update_username_form':
            $msg = update_username(
                ($_COOKIE['role_id'] <= 2 && $_COOKIE['user_id'] != $_POST['user_id'] ? $_POST['user_id'] : $_COOKIE['user_id']),
                $_POST['new_username'],
                $_POST['verify_new_username']
            );

            break;



        case 'delete_account_form':
            $msg = delete_account(
                ($_COOKIE['role_id'] <= 2 && $_COOKIE['user_id'] != $_POST['user_id'] ? $_POST['user_id'] : $_COOKIE['user_id']),
                $_POST['delete_password'],
                $_POST['delete_verify_password']
            );

            break;
    }
    echo $msg;
}

include_once 'components/head.php';

if ($_GET['action'] == 'login')
    echo login_form(($msg ? $msg : ''));
else if ($_GET['action'] == 'signup')
    echo signup_form(($msg ? $msg : ''));
else if ($_GET['action'] == 'logout')
    logout();
else if ($_GET['action'] == 'view' && isset($_GET['user_id']))
    echo user_view($_GET['user_id']);

include_once 'components/foot.php';
