<?php
/**
 * FILE: public_html/journals/verify_author.php
 *
 * Called via AJAX POST from article.php popup.
 * Verifies author name + email against submission_authors table.
 *
 * POST params:
 *   id          → submission_id
 *   author_name → full name (e.g. "Ayushi Gautam")
 *   author_email→ email address
 *   doc_type    → 'certificate' | 'acceptance'
 */

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit;
}

// ── Load DB ───────────────────────────────────────────────────────────────
$configPaths = [
    __DIR__ . '/../config/db_new.php',
    __DIR__ . '/../config/db.php',
    __DIR__ . '/../../config/db_new.php',
];
foreach ($configPaths as $cp) {
    if (file_exists($cp)) { include_once $cp; break; }
}

if (!isset($pdo)) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed.']);
    exit;
}

// ── Input ─────────────────────────────────────────────────────────────────
$sid      = (int)($_POST['id']           ?? 0);
$rawName  = trim($_POST['author_name']   ?? '');
$rawEmail = trim(strtolower($_POST['author_email'] ?? ''));
$docType  = trim($_POST['doc_type']      ?? 'certificate');

if (!$sid || !$rawName || !$rawEmail) {
    echo json_encode(['status' => 'error', 'message' => 'Please fill in all fields.']);
    exit;
}

/**
 * Build a "normalized" full name from submission_authors row.
 * Strips extra spaces and joins title + first + middle + last.
 */
function buildFullName(array $a): string {
    $parts = array_filter([
        trim($a['title']       ?? ''),
        trim($a['first_name']  ?? ''),
        trim($a['middle_name'] ?? ''),
        trim($a['last_name']   ?? ''),
    ]);
    return strtolower(preg_replace('/\s+/', ' ', implode(' ', $parts)));
}

try {
    // ── Fetch all authors for this submission ─────────────────────────────
    $stmt = $pdo->prepare("
        SELECT sa.author_id, sa.first_name, sa.middle_name, sa.last_name,
               sa.title, sa.email, sa.institutional_email, sa.is_corresponding
        FROM submission_authors sa
        WHERE sa.submission_id = ?
    ");
    $stmt->execute([$sid]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($rows)) {
        echo json_encode(['status' => 'error', 'message' => 'No authors found for this article.']);
        exit;
    }

    $inputName  = strtolower(preg_replace('/\s+/', ' ', $rawName));
    $inputEmail = strtolower($rawEmail);

    $nameMatch  = false;
    $emailMatch = false;
    $fullMatch  = false;

    foreach ($rows as $a) {
        $dbName  = buildFullName($a);
        // Check both primary email and institutional email
        $dbEmail1 = strtolower(trim($a['email']               ?? ''));
        $dbEmail2 = strtolower(trim($a['institutional_email'] ?? ''));

        $nm = ($dbName === $inputName);
        $em = ($dbEmail1 === $inputEmail || $dbEmail2 === $inputEmail);

        if ($nm) $nameMatch  = true;
        if ($em) $emailMatch = true;
        if ($nm && $em) { $fullMatch = true; break; }
    }

    // ── Also try matching against users table (account email) ─────────────
    if (!$fullMatch) {
        $stmt2 = $pdo->prepare("
            SELECT u.email, u.first_name, u.middle_name, u.last_name
            FROM users u
            JOIN submissions s ON s.user_id = u.user_id
            WHERE s.submission_id = ?
            LIMIT 1
        ");
        $stmt2->execute([$sid]);
        $user = $stmt2->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $uName  = strtolower(preg_replace('/\s+/', ' ', trim(
                ($user['first_name']  ?? '') . ' ' .
                ($user['middle_name'] ?? '') . ' ' .
                ($user['last_name']   ?? '')
            )));
            $uEmail = strtolower(trim($user['email'] ?? ''));
            if ($uName === $inputName)   $nameMatch  = true;
            if ($uEmail === $inputEmail) $emailMatch = true;
            if ($uName === $inputName && $uEmail === $inputEmail) $fullMatch = true;
        }
    }

    if ($fullMatch) {
        echo json_encode([
            'status' => 'success',
            'id'     => $sid,
            'type'   => $docType,
        ]);
    } else {
        if (!$nameMatch && !$emailMatch) {
            $msg = 'Both name and email are not matching any author of this article.';
        } elseif (!$nameMatch) {
            $msg = 'Author name does not match our records for this article.';
        } elseif (!$emailMatch) {
            $msg = 'Author email does not match our records for this article.';
        } else {
            $msg = 'Name and email do not belong to the same author.';
        }
        echo json_encode(['status' => 'error', 'message' => $msg]);
    }

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error. Please try again.']);
}