<?php
/**
 * Study Approvals - Admin Panel
 * OBGYN Research & Collaboration Platform
 */

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

requireLogin();
if (!isAdmin()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Study Approvals';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Handle approval actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();

    $action = $_POST['action'] ?? '';
    $studyId = (int)($_POST['study_id'] ?? 0);
    $notes = sanitize($_POST['notes'] ?? '');

    if ($action === 'approve' && $studyId) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE studies SET
                    approval_status = 'approved',
                    approved_by = ?,
                    approved_at = NOW(),
                    approval_notes = ?
                WHERE id = ?
            ");
            $stmt->execute([$userId, $notes, $studyId]);

            logActivity('study_approved', 'studies', $studyId);

            // Notify study creator
            $stmt = $db->prepare("
                SELECT u.email, u.first_name, s.title
                FROM users u
                JOIN studies s ON s.creator_id = u.id
                WHERE s.id = ?
            ");
            $stmt->execute([$studyId]);
            $studyInfo = $stmt->fetch();

            if ($studyInfo) {
                // Send notification (you can implement email here)
                $stmt = $db->prepare("
                    INSERT INTO notifications (user_id, type, title, message, related_id)
                    VALUES (?, 'study_approved', 'Study Approved', ?, ?)
                ");
                $stmt->execute([
                    $studyInfo['creator_id'],
                    "Your study '{$studyInfo['title']}' has been approved and is now public.",
                    $studyId
                ]);
            }

            $success = 'Study approved successfully!';
        } catch (Exception $e) {
            $error = 'Failed to approve study.';
        }
    } elseif ($action === 'reject' && $studyId) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE studies SET
                    approval_status = 'rejected',
                    approved_by = ?,
                    approved_at = NOW(),
                    approval_notes = ?
                WHERE id = ?
            ");
            $stmt->execute([$userId, $notes, $studyId]);

            logActivity('study_rejected', 'studies', $studyId);

            // Notify study creator
            $stmt = $db->prepare("
                SELECT u.email, u.first_name, s.title
                FROM users u
                JOIN studies s ON s.creator_id = u.id
                WHERE s.id = ?
            ");
            $stmt->execute([$studyId]);
            $studyInfo = $stmt->fetch();

            if ($studyInfo) {
                $stmt = $db->prepare("
                    INSERT INTO notifications (user_id, type, title, message, related_id)
                    VALUES (?, 'study_rejected', 'Study Rejected', ?, ?)
                ");
                $stmt->execute([
                    $studyInfo['creator_id'],
                    "Your study '{$studyInfo['title']}' has been rejected. Reason: " . ($notes ?: 'No reason provided'),
                    $studyId
                ]);
            }

            $success = 'Study rejected successfully!';
        } catch (Exception $e) {
            $error = 'Failed to reject study.';
        }
    }
}

// Get pending studies
$db = getDB();
$stmt = $db->prepare("
    SELECT s.*, u.first_name, u.last_name, u.email,
           i.name as institution_name, c.name as category_name
    FROM studies s
    JOIN users u ON s.creator_id = u.id
    LEFT JOIN institutions i ON s.institution_id = i.id
    LEFT JOIN categories c ON s.category_id = c.id
    WHERE s.approval_status = 'pending'
    ORDER BY s.created_at DESC
");
$stmt->execute();
$pendingStudies = $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">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2"><i class="fas fa-check-circle"></i> Study Approvals</h1>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?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; ?>

            <div class="card shadow">
                <div class="card-header">
                    <h5 class="mb-0">Pending Approvals (<?php echo count($pendingStudies); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($pendingStudies)): ?>
                        <p class="text-muted text-center py-4">No studies pending approval.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Creator</th>
                                        <th>Institution</th>
                                        <th>Category</th>
                                        <th>Type</th>
                                        <th>Submitted</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pendingStudies as $study): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo e($study['title']); ?></strong>
                                            <br>
                                            <small class="text-muted"><?php echo e(substr($study['summary'], 0, 100)); ?>...</small>
                                        </td>
                                        <td>
                                            <?php echo e($study['first_name'] . ' ' . $study['last_name']); ?>
                                            <br>
                                            <small class="text-muted"><?php echo e($study['email']); ?></small>
                                        </td>
                                        <td><?php echo e($study['institution_name'] ?: 'N/A'); ?></td>
                                        <td><?php echo e($study['category_name'] ?: 'N/A'); ?></td>
                                        <td><span class="badge bg-info"><?php echo ucfirst($study['type']); ?></span></td>
                                        <td><?php echo date('M d, Y', strtotime($study['created_at'])); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-success me-1" data-bs-toggle="modal" data-bs-target="#approveModal<?php echo $study['id']; ?>">
                                                <i class="fas fa-check"></i> Approve
                                            </button>
                                            <button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#rejectModal<?php echo $study['id']; ?>">
                                                <i class="fas fa-times"></i> Reject
                                            </button>
                                        </td>
                                    </tr>

                                    <!-- Approve Modal -->
                                    <div class="modal fade" id="approveModal<?php echo $study['id']; ?>" tabindex="-1">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">Approve Study</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                </div>
                                                <form method="POST" action="">
                                                    <?php echo csrfField(); ?>
                                                    <input type="hidden" name="action" value="approve">
                                                    <input type="hidden" name="study_id" value="<?php echo $study['id']; ?>">
                                                    <div class="modal-body">
                                                        <p>Are you sure you want to approve this study?</p>
                                                        <strong><?php echo e($study['title']); ?></strong>
                                                        <div class="mt-3">
                                                            <label for="notes<?php echo $study['id']; ?>" class="form-label">Approval Notes (Optional)</label>
                                                            <textarea class="form-control" id="notes<?php echo $study['id']; ?>" name="notes" rows="3" placeholder="Add any notes for the researcher..."></textarea>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" class="btn btn-success">Approve Study</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Reject Modal -->
                                    <div class="modal fade" id="rejectModal<?php echo $study['id']; ?>" tabindex="-1">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">Reject Study</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                </div>
                                                <form method="POST" action="">
                                                    <?php echo csrfField(); ?>
                                                    <input type="hidden" name="action" value="reject">
                                                    <input type="hidden" name="study_id" value="<?php echo $study['id']; ?>">
                                                    <div class="modal-body">
                                                        <p>Are you sure you want to reject this study?</p>
                                                        <strong><?php echo e($study['title']); ?></strong>
                                                        <div class="mt-3">
                                                            <label for="reject_notes<?php echo $study['id']; ?>" class="form-label">Rejection Reason <span class="text-danger">*</span></label>
                                                            <textarea class="form-control" id="reject_notes<?php echo $study['id']; ?>" name="notes" rows="3" required placeholder="Please provide a reason for rejection..."></textarea>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" class="btn btn-danger">Reject Study</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

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