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

// CSRF protection: Generate token if not set
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}

$msg = '';
$error = '';

// Only administrators may perform any of the actions below.
$is_admin = in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true);
if ($is_admin) {

// Handle saving accepted message
if (isset($_POST['save_message']) && isset($_POST['token']) && $_POST['token'] === $_SESSION['token']) {
    $accepted_message = isset($_POST['accepted_message']) ? $_POST['accepted_message'] : '';
    settingSet('accepted_message', $accepted_message);
    $msg = '• Successfully Saved the message';
}

// Handle email confirmation
if (isset($_POST['confirm']) && !empty($_POST['cemail']) && $_POST['token'] === $_SESSION['token']) {
    $cemail = $_POST['cemail'];
    $query = "SELECT * FROM sm_poets WHERE email = :email";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':email', $cemail, PDO::PARAM_STR);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $update_query = "UPDATE sm_poets SET email_confirmed = 1 WHERE id = :id";
        $update_stmt = $pdo->prepare($update_query);
        $update_stmt->bindParam(':id', $row['id'], PDO::PARAM_INT);
        $update_stmt->execute();
        $msg = '• Successfully Confirmed the Email';
    } else {
        $error = '• Sorry, Email does not exist in your publication';
    }
}

// Handle saving status
if (isset($_POST['save_status']) && !empty($_POST['status']) && $_POST['token'] === $_SESSION['token']) {
    $status = $_POST['status'];
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    if ($id === 0) { // Insert new status
        $query = "INSERT INTO sm_status (status) VALUES (:status)";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':status', $status, PDO::PARAM_STR);
    } else { // Update existing status
        $query = "UPDATE sm_status SET status = :status WHERE id = :id";
        $stmt = $pdo->prepare($query);
        $stmt->bindParam(':status', $status, PDO::PARAM_STR);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    }

    if ($stmt->execute()) {
        $msg = '• Successfully Saved the Status';
    } else {
        $error = '• Error Saving Status';
    }
}

// Handle notification settings
if (isset($_POST['save_notification']) && $_POST['token'] === $_SESSION['token']) {
    $notification_emails = $_POST['notification_emails'];
    $notification_enabled = intval($_POST['notification_email_enabled']);
    settingSet('notification_emails', $notification_emails);
    settingSet('notification_email_enabled', $notification_enabled);
    $msg = 'Successfully Saved your Notification Settings';
}

// Handle payment to authors setting
if (isset($_POST['payment_to_authors']) && $_POST['token'] === $_SESSION['token']) {
    settingSet('payment_to_authors', $_POST['payment_to_authors']);
    $msg = 'Successfully <b>' . ($_POST['payment_to_authors'] ? 'ENABLED' : 'DISABLED') . '</b> the payment to authors';
}

// Handle deleting status (POST + CSRF token)
if (isset($_POST['delete_status']) && is_numeric($_POST['delete_status'])
    && isset($_POST['token']) && hash_equals($_SESSION['token'], (string)$_POST['token'])) {
    $delete_status = intval($_POST['delete_status']);
    $query = "UPDATE sm_submissions SET status = 0 WHERE status = :status";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':status', $delete_status, PDO::PARAM_INT);
    $stmt->execute();

    $query = "DELETE FROM sm_status WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $delete_status, PDO::PARAM_INT);
    $stmt->execute();

    $msg = '• Successfully Deleted the Status';
}

} // end $is_admin gate

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

<link rel="stylesheet" href="../styles.css"> <!-- Link to external CSS -->

<?php if ($_SESSION['editor_type'] == 'superadmin' || $_SESSION['editor_type'] == 'admin'): ?>
    <div class="container">
        <h2>Welcome Superadmin</h2>
        <span class="msg"><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></span>
        <span class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></span>
        <div class="card">
            <p><small><b>Note:</b> Writers may submit up to <b>3</b> pieces per edition. The limit applies to both regular issues and contest editions (change it in credits.php if needed).</small></p>
        </div>

        <!-- Confirm Email -->
        <div class="card">
            <form method="post">
                <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>" />
                <p>If a customer fails to receive the confirmation email at signup, you can manually confirm their email here:</p>
                <input name="cemail" type="text" size="40" placeholder="Customer's Email" class="input-field" />
                <input name="confirm" type="submit" value="Confirm Email" class="button-primary" />
            </form>
        </div>

        <!-- Accepted Message -->
        <div class="card">
            <form method="post">
                <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>" />
                <p>Enter a message that will display for accepted submissions:</p>
                <textarea name="accepted_message" cols="50" rows="5" placeholder="Enter your message here..." class="textarea"><?= htmlspecialchars(settingGet('accepted_message'), ENT_QUOTES, 'UTF-8') ?></textarea><br />
                <input name="save_message" type="submit" value="Save Message" class="button-primary" />
            </form>
        </div>

        <!-- Status Management -->
        <div class="card">
            <form method="post" action="editors-main.php">
                <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>" />
                <?php if (isset($_GET['edit-status'])): 
                    $edit_status = intval($_GET['edit-status']);
                    $query = "SELECT * FROM sm_status WHERE id = :id";
                    $stmt = $pdo->prepare($query);
                    $stmt->bindParam(':id', $edit_status, PDO::PARAM_INT);
                    $stmt->execute();
                    $row = $stmt->fetch(PDO::FETCH_ASSOC);
                ?>
                    <input name="id" type="hidden" value="<?= intval($edit_status) ?>" />
                    <p>Change <b><?= htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8') ?></b> to:</p>
                <?php endif; ?>
                <input name="status" type="text" size="40" placeholder="Enter new status" class="input-field" />
                <input name="save_status" type="submit" value="Save Status" class="button-primary" />

                <?php
                $query = "SELECT * FROM sm_status WHERE id > 2";
                $stmt = $pdo->query($query);
                $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
                if (count($result)): ?>
                    <br />
                    <?php foreach ($result as $row): ?>
                        <b>• <?= htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8') ?></b> - 
                        <a href="editors-main.php?edit-status=<?= (int)$row['id'] ?>">edit</a> |
                        <button type="submit" form="delete-status-form" name="delete_status" value="<?= (int)$row['id'] ?>" onclick="return confirm('Deleting this status will cause all submissions with this status to be marked as pending. Are you sure to delete this?');" style="background:none;border:none;color:#06c;cursor:pointer;padding:0;font:inherit;text-decoration:underline">delete</button><br />
                    <?php endforeach; ?>
                <?php endif; ?>
            </form>
            <form id="delete-status-form" method="post"><input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>" /></form>
        </div>

        <!-- Notification Settings -->
        <div class="card">
            <form method="post">
                <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8'); ?>" />
                <input type="checkbox" name="notification_email_enabled" value="1" <?= settingGet('notification_email_enabled') ? 'checked' : '' ?> /> 
                Send a staff member a notification when a new submission comes in?<br />
                (Check the box to enable this feature.)<br /><br />
                Send Notification Emails to: <small>(emails should be comma separated)</small><br />
                <textarea name="notification_emails" cols="50" rows="5" placeholder="Enter notification emails..." class="textarea"><?= htmlspecialchars(settingGet('notification_emails'), ENT_QUOTES, 'UTF-8') ?></textarea><br />
                <input name="save_notification" type="submit" value="Save Notification Settings" class="button-primary" />
            </form>
        </div>

    </div>
<?php endif; ?>

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