<?php
require_once '../config/config.php';
requireLogin();
if (!isSuperAdmin() && !isInstitutionAdmin()) redirect(SITE_URL . '/index.php');

$pageTitle = 'Content Moderation';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    $action = $_POST['action'] ?? '';
    $type = $_POST['type'] ?? '';
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    
    $db = getDB();
    $userId = getCurrentUserId();
    
    if ($action === 'approve' && $id) {
        if ($type === 'study') {
            $db->prepare("UPDATE studies SET approval_status = 'approved', approved_by = ?, approved_at = NOW() WHERE id = ?")->execute([$userId, $id]);
        } elseif ($type === 'publication') {
            $db->prepare("UPDATE publications SET approval_status = 'approved', approved_by = ? WHERE id = ?")->execute([$userId, $id]);
        }
        $success = ucfirst($type) . ' approved.';
    } elseif ($action === 'reject' && $id) {
        if ($type === 'study') {
            $db->prepare("UPDATE studies SET approval_status = 'rejected' WHERE id = ?")->execute([$id]);
        } elseif ($type === 'publication') {
            $db->prepare("UPDATE publications SET approval_status = 'rejected' WHERE id = ?")->execute([$id]);
        }
        $success = ucfirst($type) . ' rejected.';
    }
}

$db = getDB();

// Pending studies
$stmt = $db->prepare("
    SELECT s.*, u.first_name, u.last_name, 'study' as type
    FROM studies s
    JOIN users u ON s.creator_id = u.id
    WHERE s.approval_status = 'pending'
    ORDER BY s.created_at DESC
    LIMIT 10
");
$stmt->execute();
$pendingStudies = $stmt->fetchAll();

// Pending publications
$stmt = $db->prepare("
    SELECT p.*, u.first_name, u.last_name, 'publication' as type
    FROM publications p
    JOIN users u ON p.user_id = u.id
    WHERE p.approval_status = 'pending'
    ORDER BY p.created_at DESC
    LIMIT 10
");
$stmt->execute();
$pendingPublications = $stmt->fetchAll();
if (!is_array($pendingPublications)) {
    $pendingPublications = [];
}

// Pending users
$stmt = $db->prepare("
    SELECT u.*, r.name as role_name, 'user' as type
    FROM users u
    JOIN roles r ON u.role_id = r.id
    WHERE u.status = 'pending'
    ORDER BY u.created_at DESC
    LIMIT 10
");
$stmt->execute();
$pendingUsers = $stmt->fetchAll();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar-new.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <?php include 'header-bar.php'; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Pending Studies -->
            <div class="card shadow mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Pending Studies (<?php echo count((array)$pendingStudies); ?>)</h6>
                    <a href="studies.php?filter=pending" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($pendingStudies)): ?>
                        <p class="text-muted text-center py-3">No pending studies.</p>
                    <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($pendingStudies as $study): ?>
                            <div class="list-group-item">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1"><?php echo e($study['title']); ?></h6>
                                        <p class="mb-1 small text-muted">
                                            By <?php echo e($study['first_name'] . ' ' . $study['last_name']); ?> | 
                                            <?php echo date('M d, Y', strtotime($study['created_at'])); ?>
                                        </p>
                                        <p class="mb-0 small"><?php echo e(substr($study['summary'] ?? '', 0, 100)); ?>...</p>
                                    </div>
                                    <div class="btn-group ms-3">
                                        <form method="POST" style="display:inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="approve">
                                            <input type="hidden" name="type" value="study">
                                            <input type="hidden" name="id" value="<?php echo $study['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-success"><i class="fas fa-check"></i> Approve</button>
                                        </form>
                                        <form method="POST" style="display:inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="reject">
                                            <input type="hidden" name="type" value="study">
                                            <input type="hidden" name="id" value="<?php echo $study['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-warning"><i class="fas fa-times"></i> Reject</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Pending Publications -->
            <div class="card shadow mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Pending Publications (<?php echo count((array)$pendingPublications); ?>)</h6>
                    <a href="publications.php?filter=pending" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($pendingPublications)): ?>
                        <p class="text-muted text-center py-3">No pending publications.</p>
                    <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($pendingPublications as $pub): ?>
                            <div class="list-group-item">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1"><?php echo e($pub['title']); ?></h6>
                                        <p class="mb-1 small text-muted">
                                            By <?php echo e($pub['first_name'] . ' ' . $pub['last_name']); ?> | 
                                            <?php echo date('M d, Y', strtotime($pub['created_at'])); ?>
                                        </p>
                                        <?php if ($pub['journal']): ?>
                                            <p class="mb-0 small"><em><?php echo e($pub['journal']); ?></em></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="btn-group ms-3">
                                        <form method="POST" style="display:inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="approve">
                                            <input type="hidden" name="type" value="publication">
                                            <input type="hidden" name="id" value="<?php echo $pub['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-success"><i class="fas fa-check"></i> Approve</button>
                                        </form>
                                        <form method="POST" style="display:inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="reject">
                                            <input type="hidden" name="type" value="publication">
                                            <input type="hidden" name="id" value="<?php echo $pub['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-warning"><i class="fas fa-times"></i> Reject</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Pending Users -->
            <div class="card shadow mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Pending Users (<?php echo count((array)$pendingUsers); ?>)</h6>
                    <a href="users.php?status=pending" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($pendingUsers)): ?>
                        <p class="text-muted text-center py-3">No pending users.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Registered</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pendingUsers as $user): ?>
                                    <tr>
                                        <td><?php echo e($user['first_name'] . ' ' . $user['last_name']); ?></td>
                                        <td><?php echo e($user['email']); ?></td>
                                        <td><span class="badge bg-info"><?php echo e($user['role_name']); ?></span></td>
                                        <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                        <td>
                                            <a href="users.php" class="btn btn-sm btn-primary">Review</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<?php include '../templates/admin-footer.php'; ?>
