<?php
/**
 * PATCH for reviewer_profile_form.php
 * Replace the INSERT / UPDATE section in your existing form save handler
 * with this logic so that:
 *   - New profiles → saved with approval_status='pending', is_published=0
 *   - Updates to an existing LIVE profile → saved to pending_changes (JSON)
 *     with approval_status='pending', is_published stays 1 until approved
 *
 * This is a DROP-IN replacement for the save block only.
 * The rest of your form file stays the same.
 */

// ── Inside your POST handler, after collecting $formData array ────────────

// $formData should contain all the fields from the form:
// bio, current_position, total_experience_yrs, h_index, total_citations,
// orcid_id, website_url, profile_affiliation_id, education (JSON string),
// publications (JSON string), societies (JSON string), reviewing_interests

$reviewer_id = (int)$_SESSION['reviewer_id']; // from session after login
$user_id     = (int)$_SESSION['user_id'];

// Check if profile already exists
$existing = $pdo->prepare("SELECT id, is_published, approval_status FROM reviewer_public_profile WHERE reviewer_id = ?");
$existing->execute([$reviewer_id]);
$profile = $existing->fetch(PDO::FETCH_ASSOC);

if (!$profile) {
    // ── NEW PROFILE ── insert as pending
    $slug = generateSlug($user_id, $pdo); // your existing slug function

    $pdo->prepare("
        INSERT INTO reviewer_public_profile
            (reviewer_id, user_id, slug, bio, current_position, total_experience_yrs,
             h_index, total_citations, orcid_id, website_url, profile_affiliation_id,
             education, publications, societies, reviewing_interests,
             is_published, approval_status, submitted_at, version, created_at)
        VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
             0, 'pending', NOW(), 1, NOW())
    ")->execute([
        $reviewer_id, $user_id, $slug,
        $formData['bio'],
        $formData['current_position'],
        $formData['total_experience_yrs'],
        $formData['h_index'],
        $formData['total_citations'],
        $formData['orcid_id'],
        $formData['website_url'],
        $formData['profile_affiliation_id'],
        $formData['education'],
        $formData['publications'],
        $formData['societies'],
        $formData['reviewing_interests'],
    ]);

    $message = 'Your profile has been submitted for review. It will be published once approved by our team.';

} else {
    // ── UPDATE ──
    // If currently live/approved → save to pending_changes for admin review
    // If not yet approved (still pending) → just overwrite the draft data directly

    if ($profile['is_published'] == 1 || $profile['approval_status'] === 'approved') {
        // Profile is live — store changes as JSON snapshot, don't overwrite live data
        $pendingSnapshot = json_encode([
            'bio'                   => $formData['bio'],
            'current_position'      => $formData['current_position'],
            'total_experience_yrs'  => $formData['total_experience_yrs'],
            'h_index'               => $formData['h_index'],
            'total_citations'       => $formData['total_citations'],
            'orcid_id'              => $formData['orcid_id'],
            'website_url'           => $formData['website_url'],
            'profile_affiliation_id'=> $formData['profile_affiliation_id'],
            'education'             => $formData['education'],
            'publications'          => $formData['publications'],
            'societies'             => $formData['societies'],
            'reviewing_interests'   => $formData['reviewing_interests'],
        ]);

        $pdo->prepare("
            UPDATE reviewer_public_profile
            SET pending_changes  = ?,
                approval_status  = 'pending',
                submitted_at     = NOW(),
                admin_note       = NULL
            WHERE id = ?
        ")->execute([$pendingSnapshot, $profile['id']]);

        $message = 'Your update has been submitted for review. Your current profile remains live while our team reviews the changes.';

    } else {
        // Profile not yet live — just update the draft fields directly
        $pdo->prepare("
            UPDATE reviewer_public_profile
            SET bio                    = ?,
                current_position       = ?,
                total_experience_yrs   = ?,
                h_index                = ?,
                total_citations        = ?,
                orcid_id               = ?,
                website_url            = ?,
                profile_affiliation_id = ?,
                education              = ?,
                publications           = ?,
                societies              = ?,
                reviewing_interests    = ?,
                approval_status        = 'pending',
                submitted_at           = NOW()
            WHERE id = ?
        ")->execute([
            $formData['bio'],
            $formData['current_position'],
            $formData['total_experience_yrs'],
            $formData['h_index'],
            $formData['total_citations'],
            $formData['orcid_id'],
            $formData['website_url'],
            $formData['profile_affiliation_id'],
            $formData['education'],
            $formData['publications'],
            $formData['societies'],
            $formData['reviewing_interests'],
            $profile['id'],
        ]);

        $message = 'Your profile has been updated and is awaiting approval.';
    }
}

// Return success (JSON if AJAX, or redirect)
echo json_encode(['success' => true, 'message' => $message]);
exit;