<?php
require_once __DIR__ . '/config/db.php';
startSession();

// No session at all — go to reviewer login
if (empty($_SESSION['user_id'])) {
    header('Location: /reviewer/login.php?msg=session_expired');
    exit;
}

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

try {
    // Step 1: check user role
    $stmt = db()->prepare(
        "SELECT user_id, role FROM users 
         WHERE user_id = ? AND is_active = 1 LIMIT 1"
    );
    $stmt->execute([$uid]);
    $user = $stmt->fetch();

    if (!$user) {
        header('Location: /reviewer/login.php?msg=session_expired');
        exit;
    }

    if (!in_array($user['role'], ['reviewer', 'both', 'editor'])) {
        // Pure author — they have no reviewer access
        header('Location: /author/dashboard.php?msg=no_reviewer_access');
        exit;
    }

    // Step 2: check reviewers table separately (don't trust JOIN)
    $stmt2 = db()->prepare(
        "SELECT id FROM reviewers WHERE user_id = ? LIMIT 1"
    );
    $stmt2->execute([$uid]);
    $reviewerRow = $stmt2->fetch();

    if ($reviewerRow) {
        // Has reviewer record — go straight to dashboard
        header('Location: /reviewer/dashboard.php');
        exit;
    }

    // Role says reviewer/both but no reviewers row yet
    // This can happen if role was manually set to 'both' 
    // but reviewer application was never approved
    // Solution: create the reviewers row automatically
    db()->prepare(
        "INSERT INTO reviewers 
         (user_id, reviewer_come_from, is_available, created_at) 
         VALUES (?, 'role_upgrade', 1, NOW())"
    )->execute([$uid]);

    header('Location: /reviewer/dashboard.php');
    exit;

} catch (PDOException $e) {
    error_log('auth_bridge error: ' . $e->getMessage());
    header('Location: /reviewer/login.php?msg=session_expired');
    exit;
}