<?php
// reviewer/decline_review.php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();

if (!isset($_SESSION['user_id'])) {
    header('Location: /reviewer/login.php');
    exit;
}

$user    = getCurrentUser();
$user_id = $user['user_id'];

if (!in_array($user['role'], ['reviewer', 'both', 'editor'])) {
    header('Location: /reviewer/login.php');
    exit;
}

$assignment_id = filter_var($_GET['assignment_id'] ?? 0, FILTER_VALIDATE_INT);
if (!$assignment_id) {
    header('Location: dashboard.php?error=invalid_assignment');
    exit;
}

try {
    $stmt = db()->prepare("SELECT id FROM reviewers WHERE user_id = ? LIMIT 1");
    $stmt->execute([$user_id]);
    $reviewer = $stmt->fetch();
    if (!$reviewer) throw new Exception("Reviewer not found.");
    $reviewer_id = $reviewer['id'];

    $stmt = db()->prepare("
        SELECT ra.*, s.tracking_code, mi.article_title AS title
        FROM review_assignments ra
        INNER JOIN submissions s ON ra.submission_id = s.submission_id
        LEFT JOIN manuscript_info mi ON s.submission_id = mi.submission_id
        WHERE ra.id = ? AND ra.reviewer_id = ? AND ra.assignment_status = 'request_sent'
    ");
    $stmt->execute([$assignment_id, $reviewer_id]);
    $assignment = $stmt->fetch();

    if (!$assignment) {
        header('Location: dashboard.php?error=already_processed');
        exit;
    }

    // Try with declined_date, fallback without it
    try {
        db()->prepare("
            UPDATE review_assignments
            SET assignment_status = 'declined', declined_date = NOW()
            WHERE id = ?
        ")->execute([$assignment_id]);
    } catch (PDOException $e) {
        db()->prepare("
            UPDATE review_assignments
            SET assignment_status = 'declined'
            WHERE id = ?
        ")->execute([$assignment_id]);
    }

    // Non-fatal email
    try {
        if (function_exists('sendEmail') && defined('ADMIN_EMAIL')) {
            $admin_subject = "Reviewer Declined Assignment — " . ($assignment['tracking_code'] ?? '');
            $admin_body    = "
                <p>A reviewer has declined a review invitation.</p>
                <p><strong>Manuscript:</strong> " . htmlspecialchars($assignment['title'] ?? 'Untitled') . "</p>
                <p><strong>Tracking Code:</strong> " . htmlspecialchars($assignment['tracking_code'] ?? '') . "</p>
                <p>Please assign another reviewer at your earliest convenience.</p>
            ";
            sendEmail(ADMIN_EMAIL, 'Editorial Office', $admin_subject, $admin_body);
        }
    } catch (Exception $emailEx) {
        error_log('decline email error (non-fatal): ' . $emailEx->getMessage());
    }

    header('Location: dashboard.php?declined=1');
    exit;

} catch (Exception $e) {
    error_log("decline_review error: " . $e->getMessage());
    header('Location: dashboard.php?error=' . urlencode($e->getMessage()));
    exit;
}