<?php

require_once('../common.php');
require_once('checklogin.php');
if (($_SESSION['editor_type'] ?? '') !== 'superadmin') {
    http_response_code(403);
    exit('Access denied. Staff management is restricted to the super administrator.');
}
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
include_once('header.php');
include_once('editors-menu.php');

// Database connection using PDO for compatibility
$pdo = db();  
$errors = array();

if (isset($_POST['submit'])) {
    // CSRF check
    if (!isset($_POST['token']) || !hash_equals($_SESSION['token'], (string)$_POST['token'])) {
        $errors['csrf'] = 'Invalid request. Please reload and try again.';
    }
    // Validate inputs
    if (empty($_POST['first_name'])) {
        $errors['first_name'] = 'Please enter the first name.';
    }
    if (empty($_POST['last_name'])) {
        $errors['last_name'] = 'Please enter the last name.';
    }
    if (empty($_POST['phone'])) {
        $errors['phone'] = 'Please enter a phone number.';
    }
    if (empty($_POST['email'])) {
        $errors['email'] = 'Please enter the email address.';
    }
    if (editorEmailExists($_POST['email']) && intval($_POST['id']) == 0) {
        $errors['email'] = 'Sorry. This email address is already in use.';
    }
    if (!validEmail(trim($_POST['email']))) {
        $errors['email'] = 'Sorry. The email address entered is not valid.';
    }
    if (empty($_POST['password']) && intval($_POST['id']) == 0) {
        $errors['password'] = 'Please enter a password.';
    }
    if (empty($_POST['user_type'])) {
        $errors['user_type'] = 'Please choose the user role.';
    } elseif (!in_array($_POST['user_type'], ['admin', 'editor', 'reader'], true)) {
        $errors['user_type'] = 'Invalid user role selected.';
    }

    if (!count($errors)) {
        // Use prepared statements with PDO
        if (intval($_POST['id']) == 0) {
            // Insert new editor
            $query = "INSERT INTO sm_editors (first_name, last_name, email, phone, password, user_type, date_added) 
                      VALUES (:first_name, :last_name, :email, :phone, :password, :user_type, :date_added)";
            $stmt = $pdo->prepare($query);
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $date_added = date('Y-m-d H:i:s');
            $stmt->bindParam(':first_name', $_POST['first_name']);
            $stmt->bindParam(':last_name', $_POST['last_name']);
            $stmt->bindParam(':email', $_POST['email']);
            $stmt->bindParam(':phone', $_POST['phone']);
            $stmt->bindParam(':password', $password);
            $stmt->bindParam(':user_type', $_POST['user_type']);
            $stmt->bindParam(':date_added', $date_added);
        } else {
            // Update existing editor
            $query = "UPDATE sm_editors 
                      SET first_name = :first_name, last_name = :last_name, email = :email, phone = :phone, user_type = :user_type";
            if (!empty($_POST['password'])) {
                $query .= ", password = :password";
            }
            $query .= " WHERE id = :id";
            $stmt = $pdo->prepare($query);
            $stmt->bindParam(':first_name', $_POST['first_name']);
            $stmt->bindParam(':last_name', $_POST['last_name']);
            $stmt->bindParam(':email', $_POST['email']);
            $stmt->bindParam(':phone', $_POST['phone']);
            $stmt->bindParam(':user_type', $_POST['user_type']);
            if (!empty($_POST['password'])) {
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt->bindParam(':password', $password);
            }
            $stmt->bindParam(':id', $_POST['id']);
        }

        if ($stmt->execute()) {
            $msg = 'Successfully saved the editor.';
        }
    }
}

// Handle deletion of editor (POST + CSRF token; cannot delete yourself)
if (isset($_POST['delete']) && is_numeric($_POST['delete'])
    && isset($_POST['token']) && hash_equals($_SESSION['token'], (string)$_POST['token'])
    && (int)$_POST['delete'] !== (int)($_SESSION['editor_id'] ?? 0)) {
    $delete_id = (int)$_POST['delete'];
    $query = "DELETE FROM sm_editors WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $delete_id);
    if ($stmt->execute()) {
        $msg = 'Successfully deleted the editor.';
    }
}

// Edit editor
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $query = "SELECT * FROM sm_editors WHERE id = :id";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':id', $edit_id);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    foreach ($row as $k => $v) {
        $_POST[$k] = $v;
    }
}

?>
<style>
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        background-color: #f9f9f9;
    }
    .container {
        max-width: 800px;
        margin: 20px auto;
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    h2, h3 {
        text-align: center;
    }
    form {
        margin-bottom: 20px;
    }
    form p {
        margin: 10px 0;
    }
    input[type="text"], input[type="email"], input[type="password"], input[type="submit"], input[type="button"], select {
        width: calc(100% - 20px);
        padding: 8px;
        margin: 5px 0;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        margin: 20px 0;
    }
    th, td {
        padding: 10px;
        border: 1px solid #ddd;
        text-align: left;
    }
    th {
        background-color: #f4f4f4;
    }
    .error {
        color: red;
        font-size: 12px;
    }
    .msg {
        color: green;
        text-align: center;
        margin: 10px 0;
        font-size: 14px;
    }
</style>

<div class="container">
    <h2>Staff Management</h2>
    <h3>Note: Users marked as "pending" are users who have applied to be a "reader".</h3> 
    <span class="msg"><?php if (isset($msg)) { echo $msg; } ?></span>
    <form method="post">
        <input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>" />
        <input name="id" type="hidden" value="<?= isset($_POST['id']) ? (int)$_POST['id'] : 0; ?>" />
        
        <p>Firstname:<br />
            <input value="<?= isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name'], ENT_QUOTES, 'UTF-8') : ''; ?>" name="first_name" type="text" />
            <span class="error"><?= isset($errors['first_name']) ? $errors['first_name'] : ''; ?></span>
        </p>

        <p>Lastname:<br />
            <input value="<?= isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name'], ENT_QUOTES, 'UTF-8') : ''; ?>" name="last_name" type="text" />
            <span class="error"><?= isset($errors['last_name']) ? $errors['last_name'] : ''; ?></span>
        </p>

        <p>Email:<br />
            <input value="<?= isset($_POST['email']) ? htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8') : ''; ?>" name="email" type="text" />
            <span class="error"><?= isset($errors['email']) ? $errors['email'] : ''; ?></span>
        </p>

        <p>Phone Number:<br />
            <input value="<?= isset($_POST['phone']) ? htmlspecialchars($_POST['phone'], ENT_QUOTES, 'UTF-8') : ''; ?>" name="phone" type="text" />
            <span class="error"><?= isset($errors['phone']) ? $errors['phone'] : ''; ?></span>
        </p>

        <p>Password (Leave blank to keep current password):<br />
            <input value="" name="password" type="password" placeholder="Enter new password" />
            <span class="error"><?= isset($errors['password']) ? $errors['password'] : ''; ?></span>
        </p>

        <p>User Role:<br />
            <select name="user_type">
                <option value="admin" <?= isset($_POST['user_type']) && $_POST['user_type'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                <option value="editor" <?= isset($_POST['user_type']) && $_POST['user_type'] == 'editor' ? 'selected' : ''; ?>>Editor</option>
                <option value="reader" <?= isset($_POST['user_type']) && $_POST['user_type'] == 'reader' ? 'selected' : ''; ?>>Reader</option>
            </select>
            <span class="error"><?= isset($errors['user_type']) ? $errors['user_type'] : ''; ?></span>
        </p>

        <input name="submit" value="Save" type="submit" /> 
        <?php if (isset($_GET['edit'])) { ?>
            <input onclick="location.href = 'editors.php';" type="button" value="Cancel" />
        <?php } ?>
    </form>

    <table>
        <tr>
            <th>Editor ID</th>
            <th>Name</th>
            <th>Contact Information</th>
            <th>Added</th>
            <th>Role</th>
            <th>Actions</th>
        </tr>
        <?php
        $query = "SELECT * FROM sm_editors ORDER BY id";
        $stmt = $pdo->query($query);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($result as $row) {
            ?>
            <tr>
                <td><?= (int)$row['id'] ?></td>
                <td><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name'], ENT_QUOTES, 'UTF-8') ?></td>
                <td>
                    <?= htmlspecialchars($row['phone'], ENT_QUOTES, 'UTF-8') ?><br />
                    <a href="mailto:<?= htmlspecialchars($row['email'], ENT_QUOTES, 'UTF-8') ?>">
                        <?= htmlspecialchars($row['email'], ENT_QUOTES, 'UTF-8') ?>
                    </a>
                </td>
                <td><?= date('M. d, Y h:ia', strtotime($row['date_added'])) ?></td>
                <td><?= htmlspecialchars($row['user_type'], ENT_QUOTES, 'UTF-8') ?></td>
                <td>
                    [<a href="editors.php?edit=<?= (int)$row['id'] ?>">EDIT</a>] 
                    [<form method="post" style="display:inline" onsubmit="return confirm('Are you sure to delete this editor?');"><input type="hidden" name="token" value="<?= htmlspecialchars($_SESSION['token'], ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="delete" value="<?= (int)$row['id'] ?>"><button type="submit" style="background:none;border:none;color:#06c;cursor:pointer;padding:0;font:inherit">DELETE</button></form>]
                </td>
            </tr>
            <?php
        }
        ?>
    </table>
</div>

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