<?php
/**
 * Create New Study
 * OBGYN Research & Collaboration Platform
 */

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

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

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

// Get institutions and categories
$db = getDB();
$stmt = $db->prepare("SELECT id, name FROM institutions WHERE status = 'active' ORDER BY name");
$stmt->execute();
$institutions = $stmt->fetchAll();

$stmt = $db->prepare("SELECT id, name FROM categories ORDER BY name");
$stmt->execute();
$categories = $stmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $title = sanitize($_POST['title'] ?? '');
    $type = sanitize($_POST['type'] ?? '');
    $summary = sanitize($_POST['summary'] ?? '');
    $objectives = sanitize($_POST['objectives'] ?? '');
    $methodology = sanitize($_POST['methodology'] ?? '');
    $institutionId = !empty($_POST['institution_id']) ? (int)$_POST['institution_id'] : null;
    $categoryId = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $startDate = $_POST['start_date'] ?? null;
    $endDate = $_POST['end_date'] ?? null;
    $isCollaborative = isset($_POST['is_collaborative']) ? 1 : 0;
    $isPublic = isset($_POST['is_public']) ? 1 : 0;
    
    if (empty($title)) {
        $error = 'Study title is required.';
    } elseif (empty($type)) {
        $error = 'Study type is required.';
    } else {
        try {
            // Generate slug
            $slug = generateSlug($title);
            
            // Check if slug exists
            $stmt = $db->prepare("SELECT id FROM studies WHERE slug = ?");
            $stmt->execute([$slug]);
            if ($stmt->fetch()) {
                $slug = $slug . '-' . time();
            }
            
            // Insert study
            $stmt = $db->prepare("
                INSERT INTO studies (
                    title, slug, creator_id, institution_id, category_id, type,
                    summary, objectives, methodology, start_date, end_date,
                    is_collaborative, is_public, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft')
            ");
            
            $stmt->execute([
                $title, $slug, $userId, $institutionId, $categoryId, $type,
                $summary, $objectives, $methodology, $startDate, $endDate,
                $isCollaborative, $isPublic
            ]);
            
            $studyId = $db->lastInsertId();
            
            // Update studies count
            $stmt = $db->prepare("
                UPDATE researcher_profiles 
                SET studies_count = studies_count + 1 
                WHERE user_id = ?
            ");
            $stmt->execute([$userId]);
            
            // Log activity
            logActivity('study_created', 'studies', $studyId);
            
            $success = 'Study created successfully!';
            redirect(SITE_URL . '/researcher/edit-study.php?id=' . $studyId);
            
        } catch (Exception $e) {
            error_log("Study creation error: " . $e->getMessage());
            $error = 'Failed to create study. Please try again.';
        }
    }
}

include '../templates/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-plus"></i> Create New Study</h1>
                <a href="studies.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Studies
                </a>
            </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; ?>

            <form method="POST" action="" class="needs-validation" novalidate>
                <?php echo csrfField(); ?>

                <div class="card shadow mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-info-circle"></i> Basic Information</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="title" class="form-label">Study Title *</label>
                            <input type="text" class="form-control" id="title" name="title" required
                                   placeholder="Enter a descriptive title for your study">
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="type" class="form-label">Study Type *</label>
                                <select class="form-select" id="type" name="type" required>
                                    <option value="">Select type...</option>
                                    <option value="clinical">Clinical</option>
                                    <option value="surgical">Surgical</option>
                                    <option value="fertility">Fertility</option>
                                    <option value="urogynecology">Urogynecology</option>
                                    <option value="menopause">Menopause</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="category_id" class="form-label">Category</label>
                                <select class="form-select" id="category_id" name="category_id">
                                    <option value="">Select category...</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>"><?php echo e($cat['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="summary" class="form-label">Summary</label>
                            <textarea class="form-control" id="summary" name="summary" rows="3"
                                      placeholder="Brief summary of the study"></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="objectives" class="form-label">Objectives</label>
                            <textarea class="form-control" id="objectives" name="objectives" rows="4"
                                      placeholder="Study objectives and goals"></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="methodology" class="form-label">Methodology</label>
                            <textarea class="form-control" id="methodology" name="methodology" rows="4"
                                      placeholder="Research methodology and approach"></textarea>
                        </div>
                    </div>
                </div>

                <div class="card shadow mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-calendar"></i> Timeline & Institution</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="start_date" class="form-label">Start Date</label>
                                <input type="date" class="form-control" id="start_date" name="start_date">
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="end_date" class="form-label">End Date</label>
                                <input type="date" class="form-control" id="end_date" name="end_date">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="institution_id" class="form-label">Institution</label>
                            <select class="form-select" id="institution_id" name="institution_id">
                                <option value="">Select institution...</option>
                                <?php foreach ($institutions as $inst): ?>
                                    <option value="<?php echo $inst['id']; ?>"><?php echo e($inst['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="card shadow mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-cog"></i> Settings</h5>
                    </div>
                    <div class="card-body">
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="is_collaborative" name="is_collaborative">
                            <label class="form-check-label" for="is_collaborative">
                                <strong>Collaborative Study</strong><br>
                                <small class="text-muted">Allow other researchers to collaborate on this study</small>
                            </label>
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="is_public" name="is_public" checked>
                            <label class="form-check-label" for="is_public">
                                <strong>Public Visibility</strong><br>
                                <small class="text-muted">Make this study visible to other researchers</small>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="d-flex justify-content-between mb-4">
                    <a href="studies.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Create Study
                    </button>
                </div>
            </form>
        </main>
    </div>
</div>

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