<?php
require_once('../common.php');
require_once('checklogin.php');

// Function to sanitize user input and prevent XSS
function sanitize_input($input) {
    return htmlspecialchars(trim((string)($input ?? '')), ENT_QUOTES, 'UTF-8');
}

// Function to generate CSRF token
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Function to validate CSRF token
function validate_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$token);
}

// The session is already started by checklogin.php; only start it here if needed.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$msg = '';

// Process form submission with CSRF validation
if (isset($_POST['save'])) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        die('Invalid CSRF token');
    }

    // Loop through ratings and save to the database using a prepared statement
    $stmt = $pdo->prepare("INSERT INTO sm_submissions_ratings (submission_id, reader_id, rating, date_rated) VALUES (:submission_id, :reader_id, :rating, :date_rated)");
    $sids = $_POST['sids'] ?? [];
    for ($i = 0; $i < count($sids); $i++) {
        $rating = intval($_POST['rating'][$i] ?? 0);
        $submission_id = intval($sids[$i]);
        $reader_id = intval($_SESSION['editor_id']);
        $date_rated = date('Y-m-d H:i:s');

        if ($rating != 0) {
            $stmt->bindValue(':submission_id', $submission_id, PDO::PARAM_INT);
            $stmt->bindValue(':reader_id',     $reader_id,     PDO::PARAM_INT);
            $stmt->bindValue(':rating',        $rating,        PDO::PARAM_INT);
            $stmt->bindValue(':date_rated',    $date_rated,    PDO::PARAM_STR);
            $stmt->execute();
        }
    }

    $msg = 'Successfully Saved Your Ratings!';
}

include_once('header.php');
include_once('editors-menu.php');
?>

<center><h2>Readers Area</h2></center>

<div style="float:left;width:80%;">
    <span class="msg"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></span>

    <form method="POST">
        <input type="hidden" name="csrf_token" value="<?php echo generate_csrf_token(); ?>">
        <div style="background-color:#E0E0E0;padding:10px;position:fixed;left:0px;width:300px;border:1px solid #A0A0A0;">
            <input type="submit" value="Save Ratings" name="save" />
        </div>
        <div style="height:50px;">&nbsp;</div>

        <?php
        // Get rated submissions
        $stmt = $pdo->prepare("SELECT submission_id FROM sm_submissions_ratings WHERE reader_id = :reader_id");
        $stmt->bindValue(':reader_id', (int)$_SESSION['editor_id'], PDO::PARAM_INT);
        $stmt->execute();

        $ratedSubmissions = array(0); // Default list of rated submissions
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $ratedSubmissions[] = (int)$row['submission_id'];
        }

        // Get unrated submissions. $ratedSubmissions contains only integers, so
        // it is safe to interpolate into the NOT IN clause.
        $notIn = implode(',', array_map('intval', $ratedSubmissions));
        $query = "SELECT a.*, a.id AS sid
                  FROM sm_submissions AS a
                  INNER JOIN sm_poets AS b ON a.poetid = b.id
                  WHERE a.status = 0 AND a.id NOT IN ($notIn)
                  ORDER BY a.date_submitted";
        $result = $pdo->query($query);

        foreach ($result as $row) {
            foreach ($row as $k => $v) {
                $row[$k] = stripslashes((string)($v ?? ''));
            }
        ?>

        <div style="float:left;width:230px;padding:10px;margin-right:10px;margin-bottom:10px;border:1px solid #A0A0A0;text-align:center;">
            <a href="view-submission.php?id=<?php echo (int)$row['sid']; ?>"><?php echo sanitize_input($row['title']); ?></a>

            <br /><br />
            <input type="hidden" name="sids[]" value="<?php echo (int)$row['sid']; ?>" />
            Rate:
            <select name="rating[]">
                <option value="0">Choose Your Rating</option>
                <?php for ($i = 1; $i <= 10; $i++) { ?>
                    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                <?php } ?>
            </select>
        </div>

        <?php } ?>
    </form>
</div>

<div style="float:left;width:20%;">
    <b>Your Recent Ratings</b>

    <?php
    // Display recent ratings
    $stmt = $pdo->prepare("SELECT * FROM sm_submissions_ratings WHERE reader_id = :reader_id ORDER BY id DESC LIMIT 20");
    $stmt->bindValue(':reader_id', (int)$_SESSION['editor_id'], PDO::PARAM_INT);
    $stmt->execute();

    while ($ratedSubmission = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $sub = getPoem($ratedSubmission['submission_id']);
    ?>

    <div style="border:1px solid black;padding:5px;width:220px;margin-top:10px;">
        <div style="float:left;width:50px;text-align:center;border-right:1px solid black;">
            <small>You</small><br />
            <b><?php echo sanitize_input($ratedSubmission['rating']); ?></b><br />
            <small>Avg</small><br />
            <b style="color:#00994D;"><?php echo htmlspecialchars((string)getAverageRating($ratedSubmission['submission_id']), ENT_QUOTES, 'UTF-8'); ?></b>
        </div>
        <div style="float:left;width:150px;font-size:10px;text-align:center;">
            Recent ratings by readers. Here you can see how you rated a submission, and how your rating compares to other readers.
        </div>
        <br style="clear:both;" />
    </div>

    <?php } ?>
</div>

<br style="clear:both;" />

<?php
include_once('footer.php');
?>
