<?php
require 'auth.php';
require 'db.php';

// Enable error display for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Only allow 'publisher' role
if ($_SESSION['role'] !== 'publisher') {
    http_response_code(403);
    die("Access Denied");
}

$paper_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($paper_id <= 0) {
    http_response_code(400);
    die("Invalid or missing paper ID.");
}

// Fetch submitted paper
$stmt = $pdo->prepare("SELECT * FROM submitted_papers WHERE id = ?");
$stmt->execute([$paper_id]);
$paper = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$paper) {
    http_response_code(404);
    die("Submitted paper not found.");
}

// Load volumes
$volumes = $pdo->query("SELECT id, year, volume_number FROM volumes ORDER BY year DESC, volume_number DESC")->fetchAll();

$successMsg = '';
$errorMsg = '';

// Safe escape helper
function esc($str)
{
    return htmlspecialchars((string) $str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $review1 = trim($_POST['review1'] ?? '');
    $review2 = trim($_POST['review2'] ?? '');
    $review3 = trim($_POST['review3'] ?? '');
    $volume_id = isset($_POST['volume_id']) ? intval($_POST['volume_id']) : 0;

    if (!$volume_id) {
        $errorMsg = "❌ Please select a volume.";
    } elseif ($review1 === '' || $review2 === '' || $review3 === '') {
        $errorMsg = "❌ All three review comments are required.";
    } else {
        // Confirm volume exists
        $volCheck = $pdo->prepare("SELECT COUNT(*) FROM volumes WHERE id = ?");
        $volCheck->execute([$volume_id]);
        if (!$volCheck->fetchColumn()) {
            $errorMsg = "❌ Selected volume does not exist.";
        }
    }

    if (!$errorMsg) {
        try {
            $pdo->beginTransaction();

            // Insert into papers table
            $sql = "
                INSERT INTO papers (
                    title, abstract, keywords, pdf_path, is_peer_reviewed, status, submission_date, volume_id,
                    registered_author_id,
                    author1_name, author1_affiliation,
                    author2_name, author2_affiliation,
                    author3_name, author3_affiliation,
                    author4_name, author4_affiliation,
                    fee_structure, transaction_id, payment_slip_path
                ) VALUES (
                    ?, ?, ?, ?, ?, 'Published', NOW(), ?,
                    ?,
                    ?, ?,
                    ?, ?,
                    ?, ?,
                    ?, ?,
                    ?, ?, ?
                )
            ";

            $stmtInsert = $pdo->prepare($sql);
            $stmtInsert->execute([
                $paper['title'] ?? '',
                $paper['abstract'] ?? '',
                $paper['keywords'] ?? '',
                $paper['pdf_path'] ?? '',
                $paper['is_peer_reviewed'] ?? 0,
                $volume_id,
                $paper['registered_author_id'] ?? 0,
                $paper['author1_name'] ?? '',
                $paper['author1_affiliation'] ?? '',
                $paper['author2_name'] ?? '',
                $paper['author2_affiliation'] ?? '',
                $paper['author3_name'] ?? '',
                $paper['author3_affiliation'] ?? '',
                $paper['author4_name'] ?? '',
                $paper['author4_affiliation'] ?? '',
                $paper['fee_structure'] ?? '',
                $paper['transaction_id'] ?? '',
                $paper['payment_slip_path'] ?? '',
            ]);

            $newPaperId = $pdo->lastInsertId();

            // Insert peer review comments
            $commentStmt = $pdo->prepare("INSERT INTO peer_review_comments (paper_id, comment_number, comment_text, created_by)
                VALUES (?, ?, ?, ?)");
            $userId = $_SESSION['user_id'];
            foreach ([$review1, $review2, $review3] as $i => $commentText) {
                $commentStmt->execute([$newPaperId, $i + 1, $commentText, $userId]);
            }

            // Update status and volume_id in submitted_papers
            $updateStmt = $pdo->prepare("UPDATE submitted_papers SET status = 'Published', volume_id = ? WHERE id = ?");
            $updateStmt->execute([$volume_id, $paper_id]);

            $pdo->commit();

            $successMsg = "✅ Paper published successfully!";
            $_POST = [];

        } catch (Exception $e) {
            $pdo->rollBack();
            die("❌ Database error: " . esc($e->getMessage())); // For development, replace with friendly message on production
        }
    }
}

$page_title = "Review & Publish Submitted Paper";
include 'include/header.php';
?>

<style>
    .paper-meta h5 {
        color: #004a99;
        font-weight: 600;
        margin-bottom: 0.3rem;
    }

    .paper-meta p,
    .paper-meta ul {
        margin-bottom: 1rem;
    }
</style>

<div class="container py-5">
    <div class="card shadow-sm">
        <div class="card-body">
            <h3 class="mb-4 text-primary fw-bold">📝 Review Submitted Paper</h3>

            <?php if ($errorMsg): ?>
                <div class="alert alert-danger" role="alert"><?= esc($errorMsg) ?></div>
            <?php elseif ($successMsg): ?>
                <div class="alert alert-success" role="alert"><?= esc($successMsg) ?></div>
            <?php endif; ?>

            <div class="paper-meta mb-4">
                <h5>📄 Title:</h5>
                <p><?= esc($paper['title']) ?></p>

                <h5>🧾 Abstract:</h5>
                <p><?= nl2br(esc($paper['abstract'])) ?></p>

                <h5>🔑 Keywords:</h5>
                <p><?= esc($paper['keywords']) ?></p>

                <h5>👤 Registered Author ID:</h5>
                <p><?= (int)$paper['registered_author_id'] ?></p>

                <h5>👥 Authors & Affiliations:</h5>
                <ul>
                    <?php if (!empty($paper['author1_name'])): ?>
                        <li><?= esc($paper['author1_name']) ?> — <?= esc($paper['author1_affiliation']) ?></li>
                    <?php endif; ?>
                    <?php if (!empty($paper['author2_name'])): ?>
                        <li><?= esc($paper['author2_name']) ?> — <?= esc($paper['author2_affiliation']) ?></li>
                    <?php endif; ?>
                    <?php if (!empty($paper['author3_name'])): ?>
                        <li><?= esc($paper['author3_name']) ?> — <?= esc($paper['author3_affiliation']) ?></li>
                    <?php endif; ?>
                    <?php if (!empty($paper['author4_name'])): ?>
                        <li><?= esc($paper['author4_name']) ?> — <?= esc($paper['author4_affiliation']) ?></li>
                    <?php endif; ?>
                </ul>

                <h5>💸 Fee Structure:</h5>
                <p><?= esc($paper['fee_structure']) ?: 'None' ?></p>

                <h5>🔑 Transaction ID:</h5>
                <p><?= esc($paper['transaction_id']) ?: 'None' ?></p>

                <?php if (!empty($paper['payment_slip_path'])): ?>
                    <h5>📎 Payment Slip:</h5>
                    <a href="<?= esc($paper['payment_slip_path']) ?>" target="_blank" rel="noopener noreferrer">View Payment Slip</a>
                <?php endif; ?>

                <h5>📎 PDF:</h5>
                <a href="<?= esc($paper['pdf_path']) ?>" target="_blank" rel="noopener noreferrer"
                   class="btn btn-sm btn-outline-primary mb-4">View PDF</a>
            </div>

            <form method="post" novalidate>
                <h5>📋 Reviewer Comments</h5>
                <textarea name="review1" class="form-control mb-2" placeholder="Reviewer Comment 1" required><?= esc($_POST['review1'] ?? '') ?></textarea>
                <textarea name="review2" class="form-control mb-2" placeholder="Reviewer Comment 2" required><?= esc($_POST['review2'] ?? '') ?></textarea>
                <textarea name="review3" class="form-control mb-3" placeholder="Reviewer Comment 3" required><?= esc($_POST['review3'] ?? '') ?></textarea>

                <div class="mb-4">
                    <label for="volume_id" class="form-label">📅 Assign Volume <span class="text-danger">*</span></label>
                    <select name="volume_id" id="volume_id" class="form-select" required>
                        <option value="">-- Select Volume --</option>
                        <?php foreach ($volumes as $v): ?>
                            <option value="<?= (int)$v['id'] ?>"
                                <?= (isset($_POST['volume_id']) && $_POST['volume_id'] === (string)$v['id']) ? 'selected' : '' ?>>
                                <?= esc($v['year']) ?> - Volume <?= esc($v['volume_number']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="d-flex gap-2 flex-wrap">
                    <button type="submit" class="btn btn-success">✅ Publish Paper</button>
                    <a href="dashboard.php" class="btn btn-secondary">🔙 Cancel</a>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'include/footer.php'; ?>



this is the code of other code

i want an alike code 

which will reflect submitted_papers table

to reviewer 

and reviewer will review and add three comments and send it to papers table

change statusn to published

tables are

submitted_papers table
Full texts
id
title
abstract
keywords
pdf_path
is_peer_reviewed
status
submission_date
registered_author_id
author1_name
author1_affiliation
author2_name
author2_affiliation
author3_name
author3_affiliation
author4_name
author4_affiliation
fee_structure
transaction_id
payment_slip_path


papers table 
	id	title	abstract	keywords	pdf_path	is_peer_reviewed	status	registered_author_id	author1_name	author1_affiliation	author2_name	author2_affiliation	author3_name	author3_affiliation	author4_name	author4_affiliation	issue_id	submission_date	volume_id	fee_structure	transaction_id	payment_slip_path	views	


must be fully working 

<?php
include 'include/header.php';
?>
and
<?php
include 'include/footer.php';
?>

in blue orrange themed mobile responsive and bootstraped in php