<?php
// public_html/reviewer/generate_certificate.php
// Generates Reviewer Certificate PDF using TCPDF
// One journal (cijss → ssr1.jpg), background image same for all

// ── Error reporting: log but DO NOT output (breaks PDF headers) ──────────────
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// ── DB + Session (startSession() calls session_start() internally) ───────────
// Do NOT call session_start() here — it is handled inside startSession()
require_once __DIR__ . '/config/db.php';
startSession();

// ── TCPDF path ───────────────────────────────────────────────────────────────
$tcpdf_path = __DIR__ . '/tcpdf/tcpdf.php';
if (!file_exists($tcpdf_path)) {
    http_response_code(500);
    die('TCPDF not found at: ' . $tcpdf_path);
}
require_once $tcpdf_path;

// ── Auth guard ───────────────────────────────────────────────────────────────
// if (empty($_SESSION['user_id'])) {
//     header('Location: /login.php');
//     exit;
// }


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

// Role check — allow reviewer and both
$certUser = getCurrentUser();
if (!in_array($certUser['role'], ['reviewer', 'both', 'editor'])) {
    header('Location: /reviewer/login.php?msg=access_denied');
    exit;
}

$raw_id = isset($_GET['assignment_id']) ? $_GET['assignment_id'] : '';
if (!$raw_id || !ctype_digit((string)$raw_id)) {
    http_response_code(400);
    die('Invalid assignment ID.');
}

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

// ── 1. Reviewer name ─────────────────────────────────────────────────────────
try {
    $stmt = db()->prepare("
        SELECT first_name, last_name
        FROM users
        WHERE user_id = ?
        LIMIT 1
    ");
    $stmt->execute([$user_id]);
    $reviewer_row = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log('Certificate DB error (users): ' . $e->getMessage());
    http_response_code(500);
    die('Database error. Please try again later.');
}

if (!$reviewer_row) {
    http_response_code(404);
    die('Reviewer account not found.');
}

$reviewer_name = trim(
    ($reviewer_row['first_name'] ?? '') . ' ' . ($reviewer_row['last_name'] ?? '')
);
if (!$reviewer_name) {
    http_response_code(400);
    die('Reviewer name is missing from your profile. Please update your profile first.');
}

// ── 2. Assignment data ───────────────────────────────────────────────────────
try {
    $stmt = db()->prepare("
        SELECT
            mi.article_title  AS paper_title,
            ra.submitted_date
        FROM review_assignments ra
        INNER JOIN reviewers r        ON r.id             = ra.reviewer_id
        INNER JOIN submissions s      ON s.submission_id  = ra.submission_id
        LEFT  JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        WHERE ra.id                = ?
          AND r.user_id            = ?
          AND ra.assignment_status = 'review_submitted'
          AND ra.submitted_date   IS NOT NULL
        LIMIT 1
    ");
    $stmt->execute([$assignment_id, $user_id]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log('Certificate DB error (assignments): ' . $e->getMessage());
    http_response_code(500);
    die('Database error. Please try again later.');
}

if (!$data) {
    http_response_code(404);
    die('No completed review found for this assignment, or access denied.');
}

$paper_title    = trim($data['paper_title'] ?? 'Untitled Manuscript');
$submitted_date = $data['submitted_date'];

$month = $submitted_date ? date('F', strtotime($submitted_date)) : date('F');
$year  = $submitted_date ? date('Y', strtotime($submitted_date)) : date('Y');

// ── 3. Certificate background image ─────────────────────────────────────────
// Single journal — one background image for all certificates
$certificate_image = 'https://communeglobal.com/certificate/ssr1.jpg';

// ── 4. TCPDF — extend to suppress header/footer ──────────────────────────────
if (!class_exists('CertPDF')) {
    class CertPDF extends TCPDF {
        public function Header() {}
        public function Footer() {}
    }
}

$pdf = new CertPDF('L', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Communeglobal');
$pdf->SetAuthor('Communeglobal Editorial Office');
$pdf->SetTitle('Reviewer Certificate');
$pdf->SetSubject('Peer Review Certificate');

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0, 0, true);
$pdf->SetAutoPageBreak(false, 0);

$pdf->AddPage();

// ── 4a. Full-page background image ───────────────────────────────────────────
// A4 landscape = 297 mm wide × 210 mm tall
$pdf->Image(
    $certificate_image, // URL — TCPDF fetches remote images by default
    0,    // x
    0,    // y
    297,  // width  (full page)
    210,  // height (full page)
    'JPEG',
    '',    // link
    '',    // align
    false, // resize
    150,   // dpi
    '',    // palign
    false, // ismask
    false, // imgmask
    0      // border
);

// ══════════════════════════════════════════════════════════════════════════════
// TEXT OVERLAY — adjust X/Y (mm) to match blank fields on YOUR ssr1.jpg image
//
// A4 landscape reference:
//   Width  = 297 mm  (left→right)
//   Height = 210 mm  (top→bottom)
//
// To calibrate: open ssr1.jpg in an image editor, measure blank field positions
// as percentages, then multiply: X% × 297 = Xmm,  Y% × 210 = Ymm
// ══════════════════════════════════════════════════════════════════════════════

// ── 4b. Reviewer Name ────────────────────────────────────────────────────────
// Positioned at ~46% from top (~97mm), ~9% from left (~27mm)
$pdf->SetFont('helvetica', 'B', 24);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY(27, 94);
$pdf->Cell(180, 12, strtoupper($reviewer_name), 0, 0, 'L', false, '', 0, false, 'T', 'M');

// ── 4c. Month + Year ─────────────────────────────────────────────────────────
// Positioned at ~2% from top (~4mm), ~73% from left (~217mm)
$pdf->SetFont('helvetica', 'B', 14);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY(217, 5);
$pdf->Cell(72, 9, $month . ' ' . $year, 0, 0, 'L', false, '', 0, false, 'T', 'M');

// ── 4d. Paper Title ───────────────────────────────────────────────────────────
// Positioned at ~58% from top (~122mm), ~9% from left (~27mm)
// MultiCell used so long titles wrap gracefully (max height 28mm = ~4 lines)
$pdf->SetFont('helvetica', 'I', 12);
$pdf->SetTextColor(30, 30, 30);
$pdf->MultiCell(
    238,   // width
    7,     // line height
    $paper_title,
    0,     // border
    'L',   // align
    false, // fill
    1,     // ln (next line)
    27,    // x
    120,   // y
    true,  // reseth
    0,     // stretch
    false, // ishtml
    true,  // autopadding
    28     // maxh — clamp to 4 lines so it doesn't overflow
);

// ── 5. Output PDF as download ─────────────────────────────────────────────────
// Clean output buffer to make sure no stray whitespace is sent before headers
if (ob_get_length()) {
    ob_end_clean();
}

$safe_name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $reviewer_name);
$filename  = 'Reviewer_Certificate_' . $safe_name . '_' . $year . '.pdf';

// 'D' = force download | 'I' = open inline in browser
$pdf->Output($filename, 'D');
exit;