<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db_new.php';
include __DIR__ . '/config/auth.php';
require_page_access();

$success = '';
$error   = '';

// ── Handle Save ───────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $fields = [
            'badge_icon','badge_text','section_title','section_description','stats_banner_title',
            'card1_color','card1_icon','card1_title','card1_description','card1_link_text','card1_link_url',
            'card2_color','card2_icon','card2_title','card2_description','card2_link_text','card2_link_url',
            'card3_color','card3_icon','card3_title','card3_description','card3_link_text','card3_link_url',
            'card4_color','card4_icon','card4_title','card4_description','card4_link_text','card4_link_url',
            'stat1_color','stat1_icon','stat1_value','stat1_label',
            'stat2_color','stat2_icon','stat2_value','stat2_label',
            'stat3_color','stat3_icon','stat3_value','stat3_label',
            'stat4_color','stat4_icon','stat4_value','stat4_label',
        ];

        // Check if row exists
        $exists = $pdo->query("SELECT id FROM bfooter_details LIMIT 1")->fetch();

        $setClauses = implode(', ', array_map(fn($f) => "$f = ?", $fields));
        $values     = array_map(fn($f) => trim($_POST[$f] ?? ''), $fields);

        if ($exists) {
            $pdo->prepare("UPDATE bfooter_details SET $setClauses WHERE id = ?")->execute([...$values, $exists['id']]);
        } else {
            $cols = implode(', ', $fields);
            $phs  = implode(', ', array_fill(0, count($fields), '?'));
            $pdo->prepare("INSERT INTO bfooter_details ($cols) VALUES ($phs)")->execute($values);
        }

        $success = 'Contribute section updated successfully!';
    } catch (PDOException $e) {
        $error = 'DB Error: ' . $e->getMessage();
    }
}

// ── Fetch current data ────────────────────────────────────────────────────
try {
    $d = $pdo->query("SELECT * FROM bfooter_details LIMIT 1")->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $d = [];
}

// Fallback so form is never empty
$d = array_merge([
    'badge_icon'=>'fas fa-hands-helping','badge_text'=>'JOIN OUR COMMUNITY',
    'section_title'=>'Contribute to Scientific Excellence',
    'section_description'=>'This journal is committed to swiftly sharing innovative and impactful research.',
    'stats_banner_title'=>'Advancing Social Science for a Better Tomorrow',
    'card1_color'=>'blue',   'card1_icon'=>'fas fa-file-upload',   'card1_title'=>'Submit an Article',            'card1_description'=>'Share your groundbreaking research with the global academic community','card1_link_text'=>'Get Started','card1_link_url'=>'#',
    'card2_color'=>'purple', 'card2_icon'=>'fas fa-graduation-cap','card2_title'=>'Special Issue on Education',   'card2_description'=>'Contribute to our focused collection on educational innovation','card2_link_text'=>'Learn More','card2_link_url'=>'#',
    'card3_color'=>'green',  'card3_icon'=>'fas fa-heartbeat',     'card3_title'=>'Special Issue on Public Health','card3_description'=>'Submit research addressing critical public health challenges','card3_link_text'=>'Submit Now','card3_link_url'=>'#',
    'card4_color'=>'orange', 'card4_icon'=>'fas fa-hospital-alt',  'card4_title'=>'Healthcare Research',           'card4_description'=>'Explore opportunities in healthcare and medical social sciences','card4_link_text'=>'Explore','card4_link_url'=>'#',
    'stat1_color'=>'blue',   'stat1_icon'=>'fas fa-users',    'stat1_value'=>'10K+',  'stat1_label'=>'Active Researchers',
    'stat2_color'=>'purple', 'stat2_icon'=>'fas fa-file-alt', 'stat2_value'=>'5000+', 'stat2_label'=>'Published Papers',
    'stat3_color'=>'green',  'stat3_icon'=>'fas fa-globe',    'stat3_value'=>'150+',  'stat3_label'=>'Countries',
    'stat4_color'=>'orange', 'stat4_icon'=>'fas fa-award',    'stat4_value'=>'98%',   'stat4_label'=>'Satisfaction Rate',
], $d ?: []);

$colorOptions = ['blue','purple','green','orange','red'];

$user_name = $_SESSION['username'] ?? 'Admin';
$user_role = $_SESSION['role']     ?? 'admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contribute Section — Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family:'Roboto',sans-serif; margin:0; height:100vh; overflow:hidden; }
        body.dark { background-color:#1a202c; color:#e2e8f0; }
        .sidebar { width:250px; background:#2d3748; color:white; transition:all .3s; height:100%; position:fixed; top:0; left:0; z-index:10; overflow-y:auto; }
        .sidebar.collapsed { width:70px; }
        .sidebar.collapsed .sidebar-title { display:none; }
        .content { margin-left:250px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
        .content.collapsed-sidebar { margin-left:70px; }
        .nav-item { padding:10px 12px; cursor:pointer; transition:background .2s; display:flex; align-items:center; }
        .nav-item:hover { background:#4a5568; }
        .nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
        body.dark .bg-white { background-color:#2d3748; }
        body.dark input,body.dark select,body.dark textarea { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }
        @media(max-width:768px){ .sidebar{transform:translateX(-250px);} .sidebar.mobile-open{transform:translateX(0);} .content{margin-left:0;} }
        .fi { width:100%; border:1px solid #d1d5db; border-radius:.5rem; padding:.6rem .875rem; font-size:.875rem; color:#374151; outline:none; transition:border-color .15s,box-shadow .15s; background:white; }
        .fi:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
        .section-card { background:white; border-radius:12px; border:1px solid #e5e7eb; overflow:hidden; margin-bottom:1.25rem; }
        .section-head { padding:.875rem 1.25rem; background:#f9fafb; border-bottom:1px solid #e5e7eb; display:flex; align-items:center; gap:.5rem; font-weight:600; font-size:.875rem; color:#374151; }
        .section-body { padding:1.25rem; display:grid; gap:.875rem; }
        .col2 { grid-template-columns:1fr 1fr; }
        .col3 { grid-template-columns:1fr 1fr 1fr; }
        .col4 { grid-template-columns:1fr 1fr 1fr 1fr; }
        label.lbl { display:block; font-size:.75rem; font-weight:600; color:#6b7280; margin-bottom:.35rem; text-transform:uppercase; letter-spacing:.04em; }
        .color-pill { display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:4px; vertical-align:middle; }
        @media(max-width:768px){ .col2,.col3,.col4{ grid-template-columns:1fr; } }
    </style>
</head>
<body class="bg-gray-100">

<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>
<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

    <!-- Topbar -->
    <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
        <div class="flex items-center gap-3">
            <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block"><i class="fas fa-bars text-lg"></i></button>
            <div class="flex items-center gap-2 text-sm text-gray-500">
                <a href="pages.php" class="hover:text-blue-600"><i class="fas fa-home"></i></a>
                <i class="fas fa-chevron-right text-xs text-gray-300"></i>
                <span class="text-gray-800 font-semibold">Contribute Section</span>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <button id="darkModeToggle" class="text-gray-500 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center"><i class="fas fa-moon"></i></button>
        </div>
    </div>

    <main class="p-6 max-w-5xl">

        <div class="mb-5">
            <h1 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                <i class="fas fa-layer-group text-blue-600"></i> Contribute Section Manager
            </h1>
            <p class="text-gray-400 text-sm mt-1">Edit all content in the "Contribute to Scientific Excellence" section — bfooter.php</p>
        </div>

        <?php if ($success): ?>
        <div class="bg-green-50 border-l-4 border-green-500 text-green-700 p-4 mb-5 rounded-lg flex items-center gap-2" id="flash">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg flex items-center gap-2">
            <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <form method="POST">

            <!-- ── SECTION HEADER ── -->
            <div class="section-card">
                <div class="section-head"><i class="fas fa-heading text-indigo-500"></i> Section Header</div>
                <div class="section-body col2">
                    <div>
                        <label class="lbl">Badge Icon <span class="text-gray-400 normal-case font-normal">(Font Awesome class)</span></label>
                        <input type="text" name="badge_icon" class="fi" value="<?= htmlspecialchars($d['badge_icon']) ?>" placeholder="fas fa-hands-helping">
                    </div>
                    <div>
                        <label class="lbl">Badge Text</label>
                        <input type="text" name="badge_text" class="fi" value="<?= htmlspecialchars($d['badge_text']) ?>" placeholder="JOIN OUR COMMUNITY">
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="lbl">Section Title</label>
                        <input type="text" name="section_title" class="fi" value="<?= htmlspecialchars($d['section_title']) ?>">
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="lbl">Section Description</label>
                        <textarea name="section_description" class="fi resize-none" rows="2"><?= htmlspecialchars($d['section_description']) ?></textarea>
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="lbl">Stats Banner Title</label>
                        <input type="text" name="stats_banner_title" class="fi" value="<?= htmlspecialchars($d['stats_banner_title']) ?>">
                    </div>
                </div>
            </div>

            <!-- ── ACTION CARDS ── -->
            <?php
            $cardColors = ['card1'=>'blue','card2'=>'purple','card3'=>'green','card4'=>'orange'];
            $cardNums   = [1=>'Card 1',2=>'Card 2',3=>'Card 3',4=>'Card 4'];
            foreach ([1,2,3,4] as $n):
                $p = "card{$n}_";
                $hexMap = ['blue'=>'#0ea5e9','purple'=>'#7c3aed','green'=>'#10b981','orange'=>'#f59e0b','red'=>'#ef4444'];
                $hex = $hexMap[$d[$p.'color']] ?? '#0ea5e9';
            ?>
            <div class="section-card">
                <div class="section-head">
                    <span class="inline-block w-3 h-3 rounded-full flex-shrink-0" style="background:<?= $hex ?>"></span>
                    <i class="<?= htmlspecialchars($d[$p.'icon']) ?>" style="color:<?= $hex ?>"></i>
                    Action Card <?= $n ?> — <em class="font-normal text-gray-500"><?= htmlspecialchars($d[$p.'title']) ?></em>
                </div>
                <div class="section-body col2">
                    <div>
                        <label class="lbl">Title</label>
                        <input type="text" name="<?= $p ?>title" class="fi" value="<?= htmlspecialchars($d[$p.'title']) ?>">
                    </div>
                    <div>
                        <label class="lbl">Color</label>
                        <select name="<?= $p ?>color" class="fi">
                            <?php foreach ($colorOptions as $c): ?>
                            <option value="<?= $c ?>" <?= $d[$p.'color']===$c?'selected':'' ?>><?= ucfirst($c) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Icon <span class="text-gray-400 normal-case font-normal">(FA class)</span></label>
                        <input type="text" name="<?= $p ?>icon" class="fi" value="<?= htmlspecialchars($d[$p.'icon']) ?>" placeholder="fas fa-star">
                    </div>
                    <div>
                        <label class="lbl">Link Text</label>
                        <input type="text" name="<?= $p ?>link_text" class="fi" value="<?= htmlspecialchars($d[$p.'link_text']) ?>">
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="lbl">Description</label>
                        <textarea name="<?= $p ?>description" class="fi resize-none" rows="2"><?= htmlspecialchars($d[$p.'description']) ?></textarea>
                    </div>
                    <div style="grid-column:1/-1">
                        <label class="lbl">Link URL</label>
                        <input type="url" name="<?= $p ?>link_url" class="fi" value="<?= htmlspecialchars($d[$p.'link_url']) ?>" placeholder="https://…">
                    </div>
                </div>
            </div>
            <?php endforeach; ?>

            <!-- ── STATS ── -->
            <div class="section-card">
                <div class="section-head"><i class="fas fa-chart-bar text-green-500"></i> Stats (4 items)</div>
                <div class="section-body" style="grid-template-columns:1fr 1fr; gap:1.25rem;">
                    <?php foreach ([1,2,3,4] as $n):
                        $p   = "stat{$n}_";
                        $hex = ['blue'=>'#0ea5e9','purple'=>'#7c3aed','green'=>'#10b981','orange'=>'#f59e0b','red'=>'#ef4444'][$d[$p.'color']] ?? '#0ea5e9';
                    ?>
                    <div style="border:1px solid #e5e7eb; border-radius:10px; padding:.875rem;">
                        <div class="flex items-center gap-2 mb-3 text-sm font-semibold text-gray-600">
                            <span class="inline-block w-3 h-3 rounded-full" style="background:<?= $hex ?>"></span>
                            Stat <?= $n ?>
                        </div>
                        <div style="display:grid; grid-template-columns:1fr 1fr; gap:.625rem;">
                            <div>
                                <label class="lbl">Value</label>
                                <input type="text" name="<?= $p ?>value" class="fi" value="<?= htmlspecialchars($d[$p.'value']) ?>" placeholder="10K+">
                            </div>
                            <div>
                                <label class="lbl">Label</label>
                                <input type="text" name="<?= $p ?>label" class="fi" value="<?= htmlspecialchars($d[$p.'label']) ?>" placeholder="Active Researchers">
                            </div>
                            <div>
                                <label class="lbl">Icon</label>
                                <input type="text" name="<?= $p ?>icon" class="fi" value="<?= htmlspecialchars($d[$p.'icon']) ?>" placeholder="fas fa-users">
                            </div>
                            <div>
                                <label class="lbl">Color</label>
                                <select name="<?= $p ?>color" class="fi">
                                    <?php foreach ($colorOptions as $c): ?>
                                    <option value="<?= $c ?>" <?= $d[$p.'color']===$c?'selected':'' ?>><?= ucfirst($c) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Save button -->
            <div class="flex items-center gap-4 py-4">
                <button type="submit"
                    class="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-xl font-bold flex items-center gap-2 shadow-md transition text-sm">
                    <i class="fas fa-save"></i> Save All Changes
                </button>
                <span class="text-xs text-gray-400">All sections update in one click</span>
            </div>

        </form>
    </main>
</div>

<script>
var fl = document.getElementById('flash');
if (fl) setTimeout(function(){ fl.style.transition='opacity .5s'; fl.style.opacity='0'; setTimeout(function(){ fl.remove(); }, 500); }, 3500);

function toggleMobileSidebar(){ document.getElementById('sidebar').classList.toggle('mobile-open'); }
var sc = false;
function toggleSidebar(){
    sc = !sc;
    document.getElementById('sidebar').classList.toggle('collapsed', sc);
    document.getElementById('content').classList.toggle('collapsed-sidebar', sc);
}
document.getElementById('darkModeToggle').addEventListener('click', function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('darkMode', document.body.classList.contains('dark') ? 'enabled' : 'disabled');
});
if (localStorage.getItem('darkMode') === 'enabled'){
    document.body.classList.add('dark');
    document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}
</script>
</body>
</html>