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

error_log('RECEIVED: ' . pretty_dump($_POST));
if (isset($_POST['ajaxId'])) {
    switch ($_POST['ajaxId']) {
        case 'login':
            handle_login();
            break;
        case 'logout':
            User::logout();
            break;
        case 'newPostHTML':
            handleNewPostHTML();
            break;
        case 'newThought':
            handleNewThought();
            break;
    }
} else {
    $response = [
        'error' => pretty_dump($_POST),
    ];

    echo json_encode($response);
}

function handleNewThought()
{
    $thought = new Thought(Space::retrieveFromDB($_POST['space']), null, unserialize($_SESSION['user']), 3, 2, urldecode($_POST['thought']));
    echo json_encode(['log' => 'success']);
}

function handleNewPostHTML()
{
    // TODO: Need to plumb this into the DB via AJAX.
    // TODO: Need to store the current space in SESSION and use that to auto-select a Space
    // TODO: List the user's spaces or let them search for a space or quick select a favorited space
    $html = '
        <div class="med_width std_border center padding">
            <h3 id="newPostLabel">New Thought</h3>
            <form method="post" class="center">
                <input type="hidden" name="userID" value="' . unserialize($_SESSION['user'])->getId() . '">
                <input type="hidden" name="postType" value="Thought" id="postType">

                <div id="newThought" class="column">
                    <input type="text" name="thought" placeholder="Jot a Thought." autofocus id="thought">
                </div>
                
                <div id="newMoment" class="column" style="display: none;">
                    <input type="text" name="caption" placeholder="Caption goes here." autofocus id="caption">
                </div>

                <div id="newEssay" class="column" style="display: none;">
                    <input type="text" name="title" placeholder="Title" autofocus id="title">
                    <textarea name="markdown" placeholder="#Heading" id="markdown"></textarea>
                    <input type="text" name="excerpt" placeholder="A 2-3 sentence summary." id="excerpt">
                </div>

                <input class="button" type="submit" value="Share" id="share">
            </form>
            <div class="line std_border"></div>
            <div id="newModalNav" class="row space_between">
                <span id="newNavThought" class="link">Thought</span>
                <span id="newNavMoment" class="link">Moment</span>
                <span id="newNavEssay" class="link">Essay</span>
            </div>
        </div>
    ';

    echo json_encode(['html' => $html]);
}

function handle_login()
{
    header('Content-Type: application/json');

    $response = [];

    if (isset($_POST['username']) && isset($_POST['password'])) {  // Corrected check
        // Ensure LoginCredentials and User classes are loaded
        // e.g., require_once 'path/to/LoginCredentials.php';
        //       require_once 'path/to/User.php';

        try {
            $creds = new LoginCredentials($_POST['username'], $_POST['password']);
            $user = User::login($creds);  // Assuming User::login() can return null or throw an exception

            if ($user != null) {
                $response['status'] = 'success';  // Use a clear status field
                $response['message'] = 'Login Successful.';  // Renamed 'log' to 'message' for clarity
                $response['redirect'] = 'spaces.php?view=list';

                // Serialize the user object and store it in the session
                $_SESSION['user'] = serialize($user);
                // You might want to store specific user data instead of the whole serialized object,
                // e.g., $_SESSION['user_id'] = $user->getId(); $_SESSION['username'] = $user->getUsername();
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Incorrect username and/or password.';
            }
        } catch (Exception $e) {
            // Catch potential exceptions from LoginCredentials or User::login()
            // Log the detailed error for server-side debugging
            error_log('Login Error: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());

            $response['status'] = 'error';
            $response['message'] = 'An internal error occurred. Please try again later.';
            // Optionally, for development, you could include $e->getMessage() but not in production.
        }
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Invalid Request: Username and/or password not provided.';
    }

    echo json_encode($response);
    exit;
}
