<?php
/**
 * Publications Management - Researcher Panel
 * OBGYN Research & Collaboration Platform
 */

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

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

$pageTitle = 'My Publications';
$userId = getCurrentUserId();
$error = '';
$success = '';

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

    $action = $_POST['action'] ?? 'create';

    if ($action === 'create') {
        $title = sanitize($_POST['title'] ?? '');
        $abstract = sanitize($_POST['abstract'] ?? '');
        $authors = sanitize($_POST['authors'] ?? '');
        $journal = sanitize($_POST['journal'] ?? '');
        $publicationDate = $_POST['publication_date'] ?? null;
        $doi = sanitize($_POST['doi'] ?? '');
        $url = sanitize($_POST['url'] ?? '');

        if (empty($title) || empty($authors)) {
            $error = 'Title and authors are required.';
        } else {
            try {
                $db = getDB();
                $stmt = $db->prepare("
                    INSERT INTO publications (
                        title, abstract, authors, journal, publication_date,
                        doi, url, submitter_id, status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'submitted')
                ");
                $stmt->execute([
                    $title, $abstract, $authors, $journal, $publicationDate,
                    $doi, $url, $userId
                ]);

                logActivity('publication_submitted', 'publications', $db->lastInsertId());
                $success = 'Publication submitted successfully! It will be reviewed by administrators.';
            } catch (Exception $e) {
                $error = 'Failed to submit publication.';
            }
        }
    }
}

// Get user's publications
$db = getDB();
$stmt = $db->prepare("
    SELECT * FROM publications
    WHERE submitter_id = ?
    ORDER BY created_at DESC
");
$stmt->execute([$userId]);
$publications = $stmt->fetchAll();

include '../templates/researcher-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">
            <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-book"></i> My Publications</h1>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#submitModal">
                    <i class="fas fa-plus"></i> Submit Publication
                </button>
            </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">My Publications (<?php echo count($publications); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($publications)): ?>
                        <p class="text-muted text-center py-4">
                            <i class="fas fa-book fa-3x mb-3 text-muted"></i><br>
                            No publications submitted yet.
                        </p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Journal</th>
                                        <th>Status</th>
                                        <th>Submitted</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($publications as $pub): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo e($pub['title']); ?></strong>
                                            <br>
                                            <small class="text-muted"><?php echo e(substr($pub['authors'], 0, 50)); ?>...</small>
                                        </td>
                                        <td><?php echo e($pub['journal'] ?: 'N/A'); ?></td>
                                        <td>
                                            <span class="badge bg-<?php
                                                echo $pub['status'] === 'published' ? 'success' :
                                                     ($pub['status'] === 'submitted' ? 'warning' : 'danger');
                                            ?>">
                                                <?php echo ucfirst($pub['status']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo date('M d, Y', strtotime($pub['created_at'])); ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-info" onclick="viewPublication(<?php echo $pub['id']; ?>)">
                                                <i class="fas fa-eye"></i> View
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Submit Publication Modal -->
<div class="modal fade" id="submitModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Submit Publication</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="create">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="title" class="form-label">Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="authors" class="form-label">Authors <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="authors" name="authors"
                               placeholder="e.g., Smith J, Johnson A, Williams B" required>
                        <div class="form-text">Separate multiple authors with commas</div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="journal" class="form-label">Journal</label>
                            <input type="text" class="form-control" id="journal" name="journal">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="publication_date" class="form-label">Publication Date</label>
                            <input type="date" class="form-control" id="publication_date" name="publication_date">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="doi" class="form-label">DOI</label>
                            <input type="text" class="form-control" id="doi" name="doi"
                                   placeholder="10.xxxx/xxxxx">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="url" class="form-label">URL</label>
                            <input type="url" class="form-control" id="url" name="url">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="abstract" class="form-label">Abstract</label>
                        <textarea class="form-control" id="abstract" name="abstract" rows="4"></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-primary">Submit Publication</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function viewPublication(id) {
    // Open publication details in a modal or redirect
    window.location.href = 'publication-detail.php?id=' + id;
}
</script>

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