<?php
// ============================================================
//  debug_editorial.php
//  Place in project ROOT. Open: localhost/cijss_backend/debug_editorial.php?id=13
//  Shows exactly what is saved in DB for submission_id
// ============================================================
require_once __DIR__ . '/config/db.php';
startSession();

$sid = (int)($_GET['id'] ?? 0);
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<style>
body{font-family:monospace;font-size:13px;padding:20px;background:#f5f5f5}
h2{color:#333;margin-top:20px}
table{border-collapse:collapse;width:100%;background:#fff;margin-bottom:20px}
th,td{border:1px solid #ccc;padding:6px 10px;text-align:left;font-size:12px}
th{background:#1A7F8E;color:#fff}
tr:nth-child(even){background:#f9f9f9}
.ok{color:green;font-weight:bold}
.bad{color:red;font-weight:bold}
.section{background:#fff;border:1px solid #ddd;padding:14px;margin-bottom:16px;border-radius:4px}
pre{background:#eee;padding:10px;border-radius:4px;overflow:auto;font-size:11px}
</style>
</head>
<body>

<h1>🔍 Editorial Debug — submission_id = <?= $sid ?></h1>

<?php if (!$sid): ?>
<p class="bad">❌ No submission id. Use: ?id=13</p>
<?php exit; endif; ?>

<?php

// ── 1. Check submission_editorial table ──────────────────
echo '<div class="section"><h2>1. submission_editorial table</h2>';
try {
    $stmt = db()->prepare("SELECT * FROM submission_editorial WHERE submission_id=?");
    $stmt->execute([$sid]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        echo '<span class="ok">✅ Row found</span><br><br>';
        echo '<table><tr><th>Field</th><th>Value</th></tr>';
        foreach ($row as $k => $v) {
            echo "<tr><td>$k</td><td>" . htmlspecialchars((string)$v) . "</td></tr>";
        }
        echo '</table>';
        $ids = json_decode($row['preferred_editor_ids'], true);
        echo '<b>Decoded preferred_editor_ids:</b> <pre>' . print_r($ids, true) . '</pre>';
    } else {
        echo '<span class="bad">❌ NO ROW FOUND for submission_id=' . $sid . '</span>';
        echo '<p>This means save_editorial.php is either not being called or failing silently.</p>';
    }
} catch (Exception $e) {
    echo '<span class="bad">❌ Error: ' . $e->getMessage() . '</span>';
}
echo '</div>';

// ── 2. Check suggested_reviewers table ───────────────────
echo '<div class="section"><h2>2. suggested_reviewers table</h2>';
try {
    $stmt = db()->prepare("SELECT * FROM suggested_reviewers WHERE submission_id=? ORDER BY reviewer_type, display_order");
    $stmt->execute([$sid]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if ($rows) {
        echo '<span class="ok">✅ ' . count($rows) . ' row(s) found</span><br><br>';
        echo '<table><tr>';
        foreach (array_keys($rows[0]) as $col) echo "<th>$col</th>";
        echo '</tr>';
        foreach ($rows as $r) {
            echo '<tr>';
            foreach ($r as $v) echo '<td>' . htmlspecialchars((string)$v) . '</td>';
            echo '</tr>';
        }
        echo '</table>';
    } else {
        echo '<span class="bad">❌ NO REVIEWER ROWS found for submission_id=' . $sid . '</span>';
        echo '<p>This means either:<br>
        1. save_editorial.php is not saving reviewers<br>
        2. All fields were blank so rows were skipped<br>
        3. save_editorial.php does not exist at ajax/save_editorial.php</p>';
    }
} catch (Exception $e) {
    echo '<span class="bad">❌ Table error: ' . $e->getMessage() . '</span>';
    echo '<p>The suggested_reviewers table may not exist yet. Save once first.</p>';
}
echo '</div>';

// ── 3. Check if ajax/save_editorial.php file exists ──────
echo '<div class="section"><h2>3. File existence check</h2>';
$savePath = __DIR__ . '/ajax/save_editorial.php';
if (file_exists($savePath)) {
    echo '<span class="ok">✅ ajax/save_editorial.php EXISTS</span>';
    echo '<br>Path: ' . $savePath;
    echo '<br>Size: ' . filesize($savePath) . ' bytes';
    echo '<br>Modified: ' . date('Y-m-d H:i:s', filemtime($savePath));

    // Check if it has the key DELETE line
    $content = file_get_contents($savePath);
    if (strpos($content, 'DELETE FROM suggested_reviewers') !== false) {
        echo '<br><span class="ok">✅ Has DELETE logic</span>';
    } else {
        echo '<br><span class="bad">❌ MISSING DELETE logic — old file!</span>';
    }
    if (strpos($content, 'INSERT INTO suggested_reviewers') !== false) {
        echo '<br><span class="ok">✅ Has INSERT logic</span>';
    } else {
        echo '<br><span class="bad">❌ MISSING INSERT logic</span>';
    }
} else {
    echo '<span class="bad">❌ ajax/save_editorial.php DOES NOT EXIST at: ' . $savePath . '</span>';
    echo '<p>This is your problem! Create this file.</p>';
    // Check if ajax folder exists
    $ajaxDir = __DIR__ . '/ajax/';
    echo '<br>ajax/ directory exists: ' . (is_dir($ajaxDir) ? '<span class="ok">YES</span>' : '<span class="bad">NO — create it!</span>');
}
echo '</div>';

// ── 4. Check editorial.php file ──────────────────────────
echo '<div class="section"><h2>4. editorial.php file check</h2>';
$editPath = __DIR__ . '/editorial.php';
if (file_exists($editPath)) {
    $content = file_get_contents($editPath);
    echo 'Size: ' . filesize($editPath) . ' bytes<br>';
    echo 'Modified: ' . date('Y-m-d H:i:s', filemtime($editPath)) . '<br><br>';

    // Check for the BUG — old error display logic
    if (strpos($content, '$em ? \'style="display:none"\' : \'\'') !== false ||
        strpos($content, "\$em ? 'style=\"display:none\"' : ''") !== false) {
        echo '<span class="bad">❌ BUG FOUND: Still using OLD error display logic (errors show when fields empty on load)</span><br>';
    } else {
        echo '<span class="ok">✅ Error display logic looks fixed</span><br>';
    }

    // Check for fixed affil-clear
    if (strpos($content, "style=\"<?= \$afN ? '' : 'display:none'") !== false ||
        strpos($content, 'style="<?= $afN ?') !== false) {
        echo '<span class="ok">✅ Affil clear button always rendered</span><br>';
    } else {
        echo '<span class="bad">⚠️ Affil clear button may still use old conditional rendering</span><br>';
    }
} else {
    echo '<span class="bad">❌ editorial.php not found</span>';
}
echo '</div>';

// ── 5. Quick save test ───────────────────────────────────
echo '<div class="section"><h2>5. Manual save test</h2>';
echo '<p>Click button below to test save directly (saves 1 dummy reviewer):</p>';
echo '<button onclick="testSave()">🧪 Test Save Now</button>';
echo '<div id="testResult" style="margin-top:10px;padding:10px;background:#eee;display:none"></div>';
?>
<script>
function testSave() {
    const fd = new FormData();
    fd.append('submission_id', <?= $sid ?>);
    fd.append('data', JSON.stringify({
        preferred_editor_ids: [1],
        reviewers: [{
            reviewer_type: 'recommended',
            email: 'test@example.com',
            title: 'Dr',
            first_name: 'Test',
            middle_name: '',
            last_name: 'User',
            affiliation_id: 0,
            affiliation_name: 'Test University',
            department: 'CS',
            additional_comment: 'Debug test',
            display_order: 1
        }]
    }));
    const el = document.getElementById('testResult');
    el.style.display = 'block';
    el.innerHTML = 'Saving...';
    fetch('ajax/save_editorial.php', {method:'POST', body: fd})
        .then(r => r.text())
        .then(t => {
            el.innerHTML = '<b>Raw response:</b><br><pre>' + t.replace(/</g,'&lt;') + '</pre>';
            try {
                const d = JSON.parse(t);
                if (d.success) {
                    el.innerHTML += '<br><span style="color:green;font-weight:bold">✅ SAVE SUCCESS! Now refresh this page to see if data appears above.</span>';
                } else {
                    el.innerHTML += '<br><span style="color:red;font-weight:bold">❌ Save failed: ' + d.message + '</span>';
                }
            } catch(e) {
                el.innerHTML += '<br><span style="color:red;font-weight:bold">❌ Response is not valid JSON — PHP error above!</span>';
            }
        })
        .catch(err => el.innerHTML = '<span style="color:red">Network error: ' + err + '</span>');
}
</script>
<?php echo '</div>'; ?>

</body>
</html>