<?php
/**
 * journals.php — Public Journals Listing Page
 * FILE: public_html/journals.php
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

include_once __DIR__ . '/config/db_new.php';

$categories = [];
try {
    $categories = $pdo->query("
        SELECT c.*, COUNT(j.journal_id) AS journal_count
        FROM journal_categories c
        LEFT JOIN journals j ON j.category_id = c.category_id
        GROUP BY c.category_id
        ORDER BY c.display_order ASC, c.name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

$activeDomain = trim($_GET['domain'] ?? '');
$search       = trim($_GET['q'] ?? '');
$sortBy       = $_GET['sort'] ?? 'name';

$activeCat = null;
if ($activeDomain) {
    foreach ($categories as $c) {
        if (strcasecmp($c['name'], $activeDomain) === 0) { $activeCat = $c; break; }
    }
}

$journals = [];
$queryError = '';
try {
    $where = "WHERE 1=1";
    $params = [];
    if ($activeCat) { $where .= " AND j.category_id = ?"; $params[] = $activeCat['category_id']; }
    if ($search)    { $where .= " AND (j.name LIKE ? OR j.description LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
    $orderBy = $sortBy === 'first_letter' ? "ORDER BY SUBSTRING(j.name,1,1) ASC, j.name ASC" : "ORDER BY j.name ASC";

    $hasSubmissions = false;
    try { $pdo->query("SELECT submission_status FROM submissions LIMIT 1"); $hasSubmissions = true; } catch(PDOException $e2) {}
    $articleSubquery = $hasSubmissions
        ? "COALESCE((SELECT COUNT(*) FROM submissions sub WHERE sub.journal_id = j.journal_id AND sub.submission_status NOT IN ('draft')), 0)"
        : "0";

    $sql = "SELECT j.*, c.name AS category_name,
               COALESCE((SELECT COUNT(*) FROM specialties sp WHERE sp.journal_id = j.journal_id), 0) AS section_count,
               {$articleSubquery} AS article_count
            FROM journals j
            LEFT JOIN journal_categories c ON c.category_id = j.category_id
            {$where} {$orderBy}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $journals = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) { $queryError = $e->getMessage(); }

$totalJournals = 0;
try { $totalJournals = $pdo->query("SELECT COUNT(*) FROM journals")->fetchColumn(); } catch(PDOException $e) {}

$byLetter = [];
if ($sortBy === 'first_letter') {
    foreach ($journals as $j) { $byLetter[strtoupper(substr($j['name'],0,1))][] = $j; }
}

include __DIR__ . '/include/header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Poppins:wght@600;700;800&display=swap');
:root{--primary:#5b21b6;--primary-light:#7c3aed;--primary-dark:#4c1d95;--secondary:#0ea5e9;--success:#10b981;--warning:#f59e0b;--gray-50:#f9fafb;--gray-100:#f3f4f6;--gray-200:#e5e7eb;--gray-600:#4b5563;--gray-700:#374151;--gray-900:#111827;}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Inter',sans-serif;background:var(--gray-50);color:var(--gray-900);}
.container{max-width:1280px;margin:0 auto;padding:0 1.25rem;}
.journals-hero{background:linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#4c1d95 100%);padding:3rem 0 0;position:relative;overflow:hidden;}
.journals-hero::before{content:'';position:absolute;inset:0;background:url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");}
.hero-inner{position:relative;z-index:1;display:flex;align-items:center;justify-content:space-between;gap:2rem;margin-bottom:2.5rem;}
.hero-text h1{font-family:'Poppins',sans-serif;font-size:2.5rem;font-weight:800;color:white;line-height:1.2;margin-bottom:.75rem;}
.hero-text p{color:rgba(255,255,255,.75);font-size:1.05rem;line-height:1.6;max-width:520px;}
.hero-stat{background:rgba(255,255,255,.12);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.2);border-radius:20px;padding:1.5rem 2rem;text-align:center;color:white;flex-shrink:0;}
.hero-stat-number{font-size:3rem;font-weight:800;font-family:'Poppins',sans-serif;line-height:1;}
.hero-stat-label{font-size:.85rem;opacity:.8;margin-top:.25rem;}
.search-wrap{background:white;border-radius:14px 14px 0 0;padding:1.5rem 2rem 1rem;display:flex;gap:1rem;align-items:center;box-shadow:0 -4px 20px rgba(0,0,0,.15);flex-wrap:wrap;}
.search-input-wrap{flex:1;min-width:240px;position:relative;}
.search-input-wrap i{position:absolute;left:1rem;top:50%;transform:translateY(-50%);color:#9ca3af;font-size:.95rem;}
.search-input{width:100%;border:2px solid var(--gray-200);border-radius:10px;padding:.8rem 1rem .8rem 2.75rem;font-size:.95rem;font-family:inherit;outline:none;transition:border-color .2s;}
.search-input:focus{border-color:var(--primary);}
.search-btn{background:var(--primary);color:white;border:none;border-radius:10px;padding:.8rem 1.75rem;font-size:.95rem;font-weight:600;cursor:pointer;transition:background .2s;display:flex;align-items:center;gap:.5rem;}
.search-btn:hover{background:var(--primary-dark);}
.sort-select{border:2px solid var(--gray-200);border-radius:10px;padding:.8rem 1rem;font-size:.875rem;font-family:inherit;outline:none;transition:border-color .2s;background:white;cursor:pointer;}
.sort-select:focus{border-color:var(--primary);}
.cat-tabs-wrap{background:white;border-bottom:1px solid var(--gray-200);position:sticky;top:0;z-index:50;box-shadow:0 2px 8px rgba(0,0,0,.06);}
.cat-tabs{display:flex;overflow-x:auto;gap:0;scrollbar-width:none;padding:0 1.25rem;max-width:1280px;margin:0 auto;}
.cat-tabs::-webkit-scrollbar{display:none;}
.cat-tab{flex-shrink:0;display:flex;align-items:center;gap:.5rem;padding:1rem 1.25rem;border:none;background:none;font-family:inherit;font-size:.9rem;font-weight:500;color:var(--gray-600);cursor:pointer;text-decoration:none;border-bottom:3px solid transparent;transition:all .2s;white-space:nowrap;}
.cat-tab:hover{color:var(--primary);}
.cat-tab.active{color:var(--primary);border-bottom-color:var(--primary);font-weight:700;}
.cat-tab .count{background:var(--gray-100);color:var(--gray-600);padding:1px 7px;border-radius:20px;font-size:.75rem;font-weight:600;}
.cat-tab.active .count{background:#ede9fe;color:var(--primary);}
.results-bar{display:flex;align-items:center;justify-content:space-between;padding:1.25rem 0;flex-wrap:wrap;gap:.75rem;}
.results-count{font-size:1.5rem;font-weight:800;color:var(--gray-900);}
.results-count span{color:var(--primary);}
.results-meta{font-size:.875rem;color:var(--gray-600);}
.active-filter-tag{display:inline-flex;align-items:center;gap:.5rem;background:#ede9fe;color:var(--primary);padding:.35rem .875rem;border-radius:20px;font-size:.8rem;font-weight:600;}
.active-filter-tag a{color:var(--primary);text-decoration:none;font-size:.85rem;opacity:.7;}
.active-filter-tag a:hover{opacity:1;}
.journals-grid{display:grid;grid-template-columns:repeat(1,1fr);gap:1.5rem;padding-bottom:4rem;}
@media(min-width:640px){.journals-grid{grid-template-columns:repeat(2,1fr);}}
@media(min-width:1024px){.journals-grid{grid-template-columns:repeat(3,1fr);}}
.journal-card{background:white;border:1px solid var(--gray-200);border-radius:16px;overflow:hidden;transition:all .25s;display:flex;flex-direction:column;text-decoration:none;color:inherit;position:relative;}
.journal-card::after{content:'';position:absolute;bottom:0;left:0;right:0;height:3px;background:var(--primary);transform:scaleX(0);transition:transform .3s;}
.journal-card:hover{border-color:#c4b5fd;box-shadow:0 12px 32px rgba(91,33,182,.12);transform:translateY(-4px);}
.journal-card:hover::after{transform:scaleX(1);}
.journal-cover{height:160px;position:relative;overflow:hidden;background:linear-gradient(135deg,#f3f4f6 0%,#e9ecef 100%);flex-shrink:0;}
.journal-cover img{width:100%;height:100%;object-fit:cover;transition:transform .4s;}
.journal-card:hover .journal-cover img{transform:scale(1.05);}
.journal-cover-placeholder{width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:3rem;color:#d1d5db;}
.journal-cover-placeholder.colored{background:linear-gradient(135deg,var(--bg-start,#ede9fe),var(--bg-end,#c4b5fd));color:white;font-size:2.5rem;}
.new-badge{position:absolute;top:.75rem;right:.75rem;background:#10b981;color:white;padding:2px 10px;border-radius:20px;font-size:.7rem;font-weight:700;letter-spacing:.5px;text-transform:uppercase;}
.journal-body{padding:1.25rem;flex:1;display:flex;flex-direction:column;}
.journal-cat-tag{font-size:.7rem;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--primary);margin-bottom:.5rem;}
.journal-name{font-size:1rem;font-weight:700;color:var(--gray-900);line-height:1.4;margin-bottom:.5rem;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}
.journal-desc{font-size:.8rem;color:var(--gray-600);line-height:1.6;flex:1;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin-bottom:.875rem;}
.journal-footer{display:flex;align-items:center;justify-content:space-between;padding-top:.875rem;border-top:1px solid var(--gray-100);gap:.5rem;flex-wrap:wrap;}
.journal-stat{display:flex;align-items:center;gap:.35rem;font-size:.75rem;color:var(--gray-600);}
.journal-stat i{font-size:.65rem;color:var(--primary);}
.journal-arrow{width:28px;height:28px;background:var(--gray-100);border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--primary);font-size:.75rem;transition:all .2s;flex-shrink:0;}
.journal-card:hover .journal-arrow{background:var(--primary);color:white;}
.letter-group{margin-bottom:2.5rem;}
.letter-heading{font-size:1.75rem;font-weight:800;color:var(--primary);margin-bottom:1rem;padding-bottom:.5rem;border-bottom:2px solid #ede9fe;display:flex;align-items:center;gap:.75rem;}
.letter-heading-num{font-size:.8rem;font-weight:600;color:var(--gray-600);background:var(--gray-100);padding:2px 10px;border-radius:20px;}
.empty-state{text-align:center;padding:5rem 2rem;background:white;border-radius:16px;border:1px solid var(--gray-200);}
.empty-state i{font-size:4rem;color:#d1d5db;margin-bottom:1rem;display:block;}
.empty-state h3{font-size:1.375rem;font-weight:700;color:var(--gray-700);margin-bottom:.5rem;}
.empty-state p{color:var(--gray-600);margin-bottom:1.5rem;}
.btn-purple{display:inline-flex;align-items:center;gap:.5rem;background:var(--primary);color:white;padding:.75rem 1.75rem;border-radius:10px;font-weight:600;text-decoration:none;transition:background .2s;}
.btn-purple:hover{background:var(--primary-dark);}
@media(max-width:640px){.hero-inner{flex-direction:column;}.hero-text h1{font-size:1.75rem;}.hero-stat{width:100%;}.search-wrap{padding:1rem;}.results-count{font-size:1.2rem;}}
</style>

<div class="journals-hero">
    <div class="container">
        <div class="hero-inner">
            <div class="hero-text">
                <h1><?= $activeDomain ? htmlspecialchars($activeDomain).' Journals' : 'All Journals' ?></h1>
                <p>Discover open-access journals covering every scientific discipline. Submit your research to a global audience.</p>
            </div>
            <div class="hero-stat">
                <div class="hero-stat-number"><?= $totalJournals ?></div>
                <div class="hero-stat-label">Journals</div>
            </div>
        </div>
        <form method="GET" action="" class="search-wrap">
            <?php if($activeDomain): ?><input type="hidden" name="domain" value="<?= htmlspecialchars($activeDomain) ?>"><?php endif; ?>
            <div class="search-input-wrap">
                <i class="fas fa-search"></i>
                <input type="text" name="q" class="search-input" placeholder="Enter a keyword or subject to search" value="<?= htmlspecialchars($search) ?>">
            </div>
            <select name="sort" class="sort-select" onchange="this.form.submit()">
                <option value="name"         <?= $sortBy==='name'        ?'selected':''?>>Alphabetical</option>
                <option value="first_letter" <?= $sortBy==='first_letter'?'selected':''?>>By first letter</option>
            </select>
            <button type="submit" class="search-btn"><i class="fas fa-search"></i> Search</button>
            <?php if($search): ?>
            <a href="?<?= $activeDomain?'domain='.urlencode($activeDomain).'&':''?>sort=<?= $sortBy ?>" style="color:var(--gray-600);font-size:.875rem;text-decoration:none;display:flex;align-items:center;gap:.35rem;">
                <i class="fas fa-times"></i> Clear
            </a>
            <?php endif; ?>
        </form>
    </div>
</div>

<div class="cat-tabs-wrap">
    <div class="cat-tabs">
        <a href="journals.php<?= $search?'?q='.urlencode($search):''?>" class="cat-tab <?= !$activeDomain?'active':''?>">
            All <span class="count"><?= $totalJournals ?></span>
        </a>
        <?php foreach($categories as $c):
            if($c['name']==='All') continue;
            $isActive = $activeDomain && strcasecmp($activeDomain,$c['name'])===0;
            $url = 'journals.php?domain='.urlencode($c['name']).($search?'&q='.urlencode($search):'').'&sort='.$sortBy;
        ?>
        <a href="<?= $url ?>" class="cat-tab <?= $isActive?'active':''?>">
            <?= htmlspecialchars($c['name']) ?> <span class="count"><?= $c['journal_count'] ?></span>
        </a>
        <?php endforeach; ?>
    </div>
</div>

<div class="container" style="padding-top:1.5rem">
    <?php if(!empty($queryError)): ?>
    <div style="background:#fee2e2;border:1px solid #fca5a5;color:#991b1b;padding:12px 16px;border-radius:8px;margin-bottom:1rem;font-size:13px;"><strong>DB Error:</strong> <?= htmlspecialchars($queryError) ?></div>
    <?php endif; ?>

    <div class="results-bar">
        <div>
            <div class="results-count"><span><?= count($journals) ?></span> journal<?= count($journals)!==1?'s':''?></div>
            <div class="results-meta">
                <?= $activeDomain ? 'in <strong>'.htmlspecialchars($activeDomain).'</strong>' : 'across all disciplines' ?>
                <?= $search ? ' · matching "<strong>'.htmlspecialchars($search).'</strong>"' : '' ?>
            </div>
        </div>
        <div style="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap">
            <?php if($activeDomain): ?>
            <span class="active-filter-tag"><i class="fas fa-tag"></i> <?= htmlspecialchars($activeDomain) ?> <a href="journals.php<?= $search?'?q='.urlencode($search):''?>">✕</a></span>
            <?php endif; ?>
            <?php if($search): ?>
            <span class="active-filter-tag"><i class="fas fa-search"></i> <?= htmlspecialchars($search) ?> <a href="journals.php<?= $activeDomain?'?domain='.urlencode($activeDomain):''?>">✕</a></span>
            <?php endif; ?>
        </div>
    </div>

    <?php
    // ── Color palette ──
    $palettes = [
        ['#ede9fe','#c4b5fd'],['#dbeafe','#93c5fd'],['#d1fae5','#6ee7b7'],
        ['#fef3c7','#fcd34d'],['#fee2e2','#fca5a5'],['#e0f2fe','#7dd3fc'],
        ['#f3e8ff','#d8b4fe'],['#ecfdf5','#34d399'],
    ];

    // ── Card renderer (inline, avoids separate include file) ──
    $renderCard = function($j, $idx) use ($palettes) {
        $palette  = $palettes[$idx % count($palettes)];
        $hasImage = !empty($j['cover_image_url']);
        $letter   = strtoupper(substr($j['name'],0,1));
        $isNew    = !empty($j['created_at']) && (time()-strtotime($j['created_at'])) < (90*86400);
        $articleCount = (int)($j['article_count'] ?? 0);
        $sectionCount = (int)($j['section_count'] ?? 0);

        // ✅ CORRECT CLEAN URL → communeglobal.com/journals/social-science
        $journalUrl = '/journals/' . rawurlencode($j['slug']);
        ?>
        <a href="<?= htmlspecialchars($journalUrl) ?>" class="journal-card">
            <div class="journal-cover">
                <?php if($hasImage): ?>
                <img src="/<?= htmlspecialchars(ltrim($j['cover_image_url'],'/')) ?>" alt="<?= htmlspecialchars($j['name']) ?>" loading="lazy">
                <?php else: ?>
                <div class="journal-cover-placeholder colored" style="--bg-start:<?= $palette[0] ?>;--bg-end:<?= $palette[1] ?>">
                    <span style="font-family:'Poppins',sans-serif;font-weight:800;font-size:2.5rem;color:rgba(0,0,0,.25);"><?= $letter ?></span>
                </div>
                <?php endif; ?>
                <?php if($isNew): ?><span class="new-badge">New</span><?php endif; ?>
            </div>
            <div class="journal-body">
                <?php if(!empty($j['category_name'])): ?>
                <div class="journal-cat-tag"><?= htmlspecialchars($j['category_name']) ?></div>
                <?php endif; ?>
                <div class="journal-name"><?= htmlspecialchars($j['name']) ?></div>
                <?php if(!empty($j['description'])): ?>
                <div class="journal-desc"><?= htmlspecialchars($j['description']) ?></div>
                <?php endif; ?>
                <div class="journal-footer">
                    <div style="display:flex;gap:.875rem;flex-wrap:wrap">
                        <?php if($sectionCount > 0): ?>
                        <span class="journal-stat"><i class="fas fa-layer-group"></i> <?= $sectionCount ?> section<?= $sectionCount!=1?'s':''?></span>
                        <?php endif; ?>
                        <?php if($articleCount > 0): ?>
                        <span class="journal-stat"><i class="fas fa-file-alt"></i> <?= $articleCount ?> article<?= $articleCount!=1?'s':''?></span>
                        <?php endif; ?>
                    </div>
                    <div class="journal-arrow"><i class="fas fa-arrow-right"></i></div>
                </div>
            </div>
        </a>
        <?php
    };
    ?>

    <?php if(empty($journals)): ?>
    <div class="empty-state">
        <i class="fas fa-book-open"></i>
        <h3>No journals found</h3>
        <p><?= $search ? 'No journals match "'.htmlspecialchars($search).'".' : ($activeDomain ? 'No journals in "'.htmlspecialchars($activeDomain).'" yet.' : 'No journals published yet.') ?></p>
        <a href="journals.php" class="btn-purple"><i class="fas fa-redo"></i> View all journals</a>
    </div>

    <?php elseif($sortBy === 'first_letter'): ?>
    <?php foreach($byLetter as $letter => $letterJournals): ?>
    <div class="letter-group">
        <div class="letter-heading"><?= $letter ?> <span class="letter-heading-num"><?= count($letterJournals) ?></span></div>
        <div class="journals-grid">
            <?php foreach($letterJournals as $idx => $j): $renderCard($j, $idx); endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>

    <?php else: ?>
    <div class="journals-grid">
        <?php foreach($journals as $idx => $j): $renderCard($j, $idx); endforeach; ?>
    </div>
    <?php endif; ?>

</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('keydown', function(e) {
        if (e.key === '/' && document.activeElement.tagName !== 'INPUT') {
            e.preventDefault();
            document.querySelector('.search-input')?.focus();
        }
    });
});
</script>

<?php include __DIR__ . '/include/footer.php'; ?>