<?php
/**
 * Study Moderation
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isSuperAdmin() && !isInstitutionAdmin()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Study Moderation';
$success = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $action = $_POST['action'] ?? '';
    $studyId = isset($_POST['study_id']) ? (int)$_POST['study_id'] : 0;
    
    $db = getDB();
    $currentUserId = getCurrentUserId();
    
    if ($action === 'approve' && $studyId) {
        $stmt = $db->prepare("UPDATE studies SET approval_status = 'approved', approved_by = ?, approved_at = NOW() WHERE id = ?");
        $stmt->execute([$currentUserId, $studyId]);
        $success = 'Study approved successfully.';
    } elseif ($action === 'reject' && $studyId) {
        $stmt = $db->prepare("UPDATE studies SET approval_status = 'rejected' WHERE id = ?");
        $stmt->execute([$studyId]);
        $success = 'Study rejected.';
    } elseif ($action === 'delete' && $studyId) {
        $stmt = $db->prepare("DELETE FROM studies WHERE id = ?");
        $stmt->execute([$studyId]);
        $success = 'Study deleted successfully.';
    }
}

// Get filters
$filter = $_GET['filter'] ?? 'all';
$search = $_GET['search'] ?? '';

$db = getDB();
$where = ["1=1"];
$params = [];

if ($filter === 'pending') {
    $where[] = "s.approval_status = 'pending'";
} elseif ($filter === 'approved') {
    $where[] = "s.approval_status = 'approved'";
} elseif ($filter === 'rejected') {
    $where[] = "s.approval_status = 'rejected'";
}

if (!empty($search)) {
    $where[] = "(s.title LIKE ? OR s.summary LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$whereClause = implode(' AND ', $where);

$stmt = $db->prepare("
    SELECT s.*, u.first_name, u.last_name,
           (SELECT COUNT(*) FROM study_collaborators WHERE study_id = s.id) as collaborators_count
    FROM studies s
    JOIN users u ON s.creator_id = u.id
    WHERE $whereClause
    ORDER BY s.created_at DESC
    LIMIT 50
");
$stmt->execute($params);
$studies = $stmt->fetchAll();

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

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.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">
                    <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Filters -->
            <div class="card shadow mb-4">
                <div class="card-body">
                    <form method="GET" action="" class="row g-3">
                        <div class="col-md-4">
                            <input type="text" class="form-control" name="search" 
                                   value="<?php echo e($search); ?>" placeholder="Search studies...">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" name="filter">
                                <option value="all" <?php echo $filter === 'all' ? 'selected' : ''; ?>>All Studies</option>
                                <option value="pending" <?php echo $filter === 'pending' ? 'selected' : ''; ?>>Pending Approval</option>
                                <option value="approved" <?php echo $filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                <option value="rejected" <?php echo $filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search"></i> Filter
                            </button>
                        </div>
                        <div class="col-md-3">
                            <a href="studies.php" class="btn btn-outline-secondary w-100">
                                <i class="fas fa-redo"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Studies List -->
            <div class="card shadow">
                <div class="card-body">
                    <?php if (empty($studies)): ?>
                        <p class="text-muted text-center py-4">No studies found.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Title</th>
                                        <th>Creator</th>
                                        <th>Type</th>
                                        <th>Status</th>
                                        <th>Approval</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($studies as $study): ?>
                                    <tr>
                                        <td><?php echo $study['id']; ?></td>
                                        <td>
                                            <strong><?php echo e(substr($study['title'], 0, 50)); ?></strong>
                                            <?php if (strlen($study['title']) > 50): ?>...<?php endif; ?>
                                        </td>
                                        <td><?php echo e($study['first_name'] . ' ' . $study['last_name']); ?></td>
                                        <td><span class="badge bg-secondary"><?php echo ucfirst($study['type']); ?></span></td>
                                        <td><span class="badge bg-info"><?php echo ucfirst($study['status']); ?></span></td>
                                        <td>
                                            <?php
                                            $approvalColors = [
                                                'pending' => 'warning',
                                                'approved' => 'success',
                                                'rejected' => 'danger'
                                            ];
                                            $color = $approvalColors[$study['approval_status']] ?? 'secondary';
                                            ?>
                                            <span class="badge bg-<?php echo $color; ?>">
                                                <?php echo ucfirst($study['approval_status']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo date('M d, Y', strtotime($study['created_at'])); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <?php if ($study['approval_status'] === 'pending'): ?>
                                                    <form method="POST" action="" style="display: inline;">
                                                        <?php echo csrfField(); ?>
                                                        <input type="hidden" name="action" value="approve">
                                                        <input type="hidden" name="study_id" value="<?php echo $study['id']; ?>">
                                                        <button type="submit" class="btn btn-success" title="Approve">
                                                            <i class="fas fa-check"></i>
                                                        </button>
                                                    </form>
                                                    <form method="POST" action="" style="display: inline;">
                                                        <?php echo csrfField(); ?>
                                                        <input type="hidden" name="action" value="reject">
                                                        <input type="hidden" name="study_id" value="<?php echo $study['id']; ?>">
                                                        <button type="submit" class="btn btn-warning" title="Reject">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                                <form method="POST" action="" style="display: inline;" 
                                                      onsubmit="return confirm('Delete this study?')">
                                                    <?php echo csrfField(); ?>
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="study_id" value="<?php echo $study['id']; ?>">
                                                    <button type="submit" class="btn btn-danger" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

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