<?php
if (session_status() === PHP_SESSION_NONE) session_start();

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

$admin_name = $_SESSION['admin_name'] ?? 'Admin';
$admin_role = $_SESSION['admin_role'] ?? 'admin';

/* ================= FETCH DATA ================= */

try {
    $stmt = $pdo->prepare("SELECT * FROM editorial_application ORDER BY submitted_at DESC");
    $stmt->execute();
    $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $applications = [];
    error_log("Editorial fetch error: " . $e->getMessage());
}

$user_name = $_SESSION['username'] ?? 'Admin';
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editorial Applications - RSIS CRM</title>

<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            margin: 0;
            height: 100vh;
            overflow: hidden;
            transition: background-color 0.3s;
        }
        body.dark {
            background-color: #1a202c;
            color: #e2e8f0;
        }
        .sidebar {
            width: 250px;
            background: #2d3748;
            color: white;
            transition: all 0.3s ease-in-out;
            height: 100%;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 10;
            overflow-y: auto;
        }
        .sidebar.hidden {
            transform: translateX(-250px);
        }
        .sidebar.collapsed {
            width: 70px;
        }
        .sidebar.collapsed .sidebar-title {
            display: none;
        }
        .sidebar.collapsed nav ul li a span {
            display: none;
        }
        .content {
            margin-left: 250px;
            padding: 20px;
            transition: margin-left 0.3s ease-in-out;
            height: 100vh;
            overflow-y: auto;
        }
        .content.shifted {
            margin-left: 0;
        }
        .content.collapsed-sidebar {
            margin-left: 70px;
        }
        .nav-item {
            padding: 10px 15px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .nav-item:hover {
            background: #4a5568;
        }
        .nav-item.active {
            background: #4a5568;
            border-left: 4px solid #4299e1;
        }
        .bg-white {
            background-color: white;
        }
        body.dark .bg-white {
            background-color: #2d3748;
        }
        body.dark .text-gray-700 {
            color: #d1d5db;
        }
        body.dark .bg-gray-50 {
            background-color: #3f3f3f;
        }
        body.dark input, body.dark select {
            background-color: #374151;
            color: #e5e7eb;
            border-color: #4b5563;
        }
        .table-container {
            overflow-x: auto;
            max-height: 600px;
        }
        .truncate-cell {
            max-width: 200px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-250px);
            }
            .sidebar.mobile-open {
                transform: translateX(0);
            }
            .content {
                margin-left: 0;
            }
        }
        .alert {
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0.5rem;
        }
        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #10b981;
        }
        .alert-error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }
        /* COLLAPSED MODE → hide text but KEEP main icons */
        .sidebar.collapsed .nav-item span,
        .sidebar.collapsed .submenu,
        .sidebar.collapsed .submenu li,
        .sidebar.collapsed .submenu a span,
        .sidebar.collapsed button span.label {
            display: none !important;
        }
        /* Show ONLY main icon in collapsed mode */
        .sidebar.collapsed .nav-item i.main-icon {
            display: inline-block !important;
            font-size: 22px;
            margin-right: 0;
        }
        /* Hide dropdown arrow in collapsed mode */
        .sidebar.collapsed .nav-item i.arrow-icon {
            display: none !important;
        }
        /* Hide submenu completely in collapsed mode */
        .sidebar.collapsed .submenu {
            display: none !important;
        }
    </style>


<style>
body { font-family: Arial, sans-serif; }
.table-container { overflow-x: auto; max-height: 600px; }
.truncate-cell { max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
</style>
</head>

<body class="bg-gray-100">
    <!-- Mobile Toggle Button -->
    <button id="sidebarToggleBtn" 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'; ?>

    <!-- Main Content -->
    <div class="content" id="content">


<!-- HEADER -->
<div class="bg-white shadow p-4 rounded-lg mb-6 mt-5 flex justify-between items-center">
    <h1 class="text-2xl font-semibold">
        <i class="fas fa-user-edit mr-2 text-blue-600"></i>
        Editorial Applications
    </h1>

    <div class="flex items-center space-x-4">
        <span class="bg-blue-100 text-blue-800 px-4 py-2 rounded-full font-semibold">
            Total: <?php echo count($applications); ?>
        </span>

        <span>Welcome, <strong><?php echo htmlspecialchars($user_name); ?></strong></span>

        <button onclick="toggleDark()" class="text-gray-600 text-xl">
            <i class="fas fa-moon"></i>
        </button>
    </div>
</div>


<!-- TOGGLE COLUMNS -->
<div class="bg-white p-4 rounded shadow mb-6">
    <h2 class="font-semibold mb-3"><i class="fas fa-columns mr-2"></i>Toggle Columns</h2>

    <div class="grid grid-cols-2 md:grid-cols-5 gap-2 text-sm">
        <?php
        $cols = [
            'id','journal','salutation','full_name','gender','current_employment',
            'total_experience','educational_qualifications','research_area',
            'personal_email','work_email','mobile_no','whatsapp_no',
            'city','state_province','country',
            'international_publications','rsis_journal_publications',
            'how_did_you_find_us','cv_filename','submitted_at','ip_address'
        ];

        foreach($cols as $col){
            echo '<label class="flex items-center">
                    <input type="checkbox" checked class="toggle-col mr-2" data-col="'.$col.'">
                    <span>'.$col.'</span>
                  </label>';
        }
        ?>
    </div>
</div>


<!-- TABLE -->
<div class="bg-white p-6 rounded shadow">

<div class="flex justify-between mb-4">
    <h2 class="text-xl font-semibold"><i class="fas fa-table mr-2 text-green-600"></i>Applications List</h2>

    <button onclick="exportExcel()" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
        <i class="fas fa-file-excel mr-2"></i>Export
    </button>
</div>

<?php if(empty($applications)): ?>

<div class="text-center py-12 text-gray-500">
    No editorial applications found.
</div>

<?php else: ?>

<div class="table-container">
<table class="w-full text-sm text-left" id="appTable">

<thead class="bg-gray-50 sticky top-0">
<tr>
<?php foreach($cols as $col): ?>
<th class="px-4 py-3 font-semibold" data-col="<?php echo $col; ?>">
    <?php echo strtoupper(str_replace('_',' ',$col)); ?>
</th>
<?php endforeach; ?>
</tr>
</thead>

<tbody>
<?php foreach($applications as $app): ?>
<tr class="border-b hover:bg-gray-50">

<?php foreach($cols as $col): ?>
<td class="px-4 py-3 truncate-cell" data-col="<?php echo $col; ?>">

<?php
if($col === 'cv_filename'){
    if(!empty($app[$col])){
        echo '<a href="https://rsisinternational.org/website_ui/uploads/'.htmlspecialchars($app[$col]).'" target="_blank">
                <i class="fas fa-file-pdf text-red-500 text-lg"></i>
              </a>';
    } else {
        echo 'N/A';
    }
}
elseif($col === 'submitted_at'){
    echo !empty($app[$col]) ? date('Y-m-d H:i', strtotime($app[$col])) : 'N/A';
}
else{
    echo htmlspecialchars($app[$col] ?? 'N/A');
}
?>

</td>
<?php endforeach; ?>

</tr>
<?php endforeach; ?>
</tbody>

</table>
</div>

<?php endif; ?>
</div>

</div>


<!-- JS -->
<script>

/* DARK MODE */
function toggleDark(){
    document.body.classList.toggle('bg-gray-900');
    document.body.classList.toggle('text-white');
}

/* COLUMN TOGGLE */
document.querySelectorAll('.toggle-col').forEach(cb=>{
    cb.addEventListener('change', function(){
        let col = this.dataset.col;
        document.querySelectorAll('[data-col="'+col+'"]').forEach(el=>{
            el.style.display = this.checked ? '' : 'none';
        });
    });
});

/* EXPORT */
function exportExcel(){
    var table = document.getElementById("appTable");
    var wb = XLSX.utils.table_to_book(table, {sheet:"Editorial Applications"});
    XLSX.writeFile(wb, "editorial_applications.xlsx");
}

</script>

</body>
</html>
