<?php
// reviewer/accept_review.php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

$config_paths = array(
    __DIR__ . '/config/db.php',
    __DIR__ . '/../config/db.php',
    __DIR__ . '/../../common/db.php',
);
foreach ($config_paths as $path) {
    if (file_exists($path)) { require_once $path; break; }
}

if (function_exists('startSession')) {
    startSession();
} elseif (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ── Auth guard — fetch $user FIRST ──────────────────────────
if (!isset($_SESSION['user_id'])) {
    header('Location: /reviewer/login.php');
    exit;
}

$user_id = (int)$_SESSION['user_id'];

// Fetch user from DB (getCurrentUser() may not be available here)
if (function_exists('getCurrentUser')) {
    $user = getCurrentUser();
} else {
    $pdo_tmp = function_exists('db') ? db() : null;
    if ($pdo_tmp) {
        $su = $pdo_tmp->prepare("SELECT * FROM users WHERE user_id = ? LIMIT 1");
        $su->execute([$user_id]);
        $user = $su->fetch(PDO::FETCH_ASSOC);
    }
}

if (!$user || !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;
}

if (function_exists('db')) {
    $pdo = db();
}
if (!isset($pdo) || !($pdo instanceof PDO)) {
    error_log("accept_review.php: PDO not available");
    http_response_code(500);
    die('Database connection error.');
}

try {
    $stmt = $pdo->prepare("SELECT id FROM reviewers WHERE user_id = ? LIMIT 1");
    $stmt->execute([$user_id]);
    $reviewer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$reviewer) {
        error_log("accept_review.php: No reviewer row for user_id=$user_id");
        header('Location: dashboard.php?error=not_reviewer');
        exit;
    }
    $reviewer_id = (int)$reviewer['id'];

    $stmt = $pdo->prepare("
        SELECT ra.id,
               ra.submission_id,
               ra.assignment_status,
               ra.review_due_date,
               mi.article_title AS title,
               s.tracking_code,
               u.email,
               u.first_name,
               u.last_name
        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
        LEFT  JOIN users u            ON u.user_id = ?
        WHERE ra.id          = ?
          AND ra.reviewer_id = ?
    ");
    $stmt->execute([$user_id, $assignment_id, $reviewer_id]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

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

    if ($assignment['assignment_status'] !== 'request_sent') {
        header('Location: view_article.php?assignment_id=' . $assignment_id);
        exit;
    }

    // Update to accepted — try with accepted_date, fallback without
    try {
        $pdo->prepare("
            UPDATE review_assignments
            SET assignment_status = 'accepted', accepted_date = NOW()
            WHERE id = ? AND reviewer_id = ?
        ")->execute([$assignment_id, $reviewer_id]);
    } catch (PDOException $e) {
        $pdo->prepare("
            UPDATE review_assignments
            SET assignment_status = 'accepted'
            WHERE id = ? AND reviewer_id = ?
        ")->execute([$assignment_id, $reviewer_id]);
    }

    // Non-fatal confirmation email
    try {
        $name = trim(($assignment['first_name'] ?? '') . ' ' . ($assignment['last_name'] ?? '')) ?: 'Reviewer';
        $due  = !empty($assignment['review_due_date'])
              ? date('F d, Y', strtotime($assignment['review_due_date']))
              : 'the agreed deadline';
        $subject = "Review Invitation Accepted — Communeglobal";
        $body    = "<p>Dear {$name},</p>
                    <p>Thank you for accepting the review of <strong>" . htmlspecialchars($assignment['title'] ?? '') . "</strong>.</p>
                    <p>Review due: <strong>{$due}</strong></p>
                    <p>Best regards,<br>Communeglobal Editorial Team</p>";

        if (function_exists('sendEmail')) {
            sendEmail($assignment['email'], $name, $subject, $body);
        } else {
            @mail($assignment['email'], $subject, $body,
                  "MIME-Version: 1.0\r\nContent-type: text/html\r\nFrom: editorial@communeglobal.com");
        }
    } catch (Exception $e) {
        error_log("accept_review email failed (non-fatal): " . $e->getMessage());
    }

    header('Location: view_article.php?assignment_id=' . $assignment_id . '&accepted=1');
    exit;

} catch (PDOException $e) {
    error_log("accept_review.php DB error: " . $e->getMessage());
    header('Location: dashboard.php?error=db_error');
    exit;
}