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

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

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

$pageTitle = 'Edit Study';
$userId = getCurrentUserId();
$studyId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$error = '';
$success = '';

// Get study
$db = getDB();
$stmt = $db->prepare("SELECT * FROM studies WHERE id = ? AND creator_id = ?");
$stmt->execute([$studyId, $userId]);
$study = $stmt->fetch();

if (!$study) {
    redirect(SITE_URL . '/researcher/studies.php');
}

// Get collaborators
$stmt = $db->prepare("
    SELECT sc.*, u.first_name, u.last_name, u.email
    FROM study_collaborators sc
    JOIN users u ON sc.user_id = u.id
    WHERE sc.study_id = ?
    ORDER BY sc.joined_at DESC
");
$stmt->execute([$studyId]);
$collaborators = $stmt->fetchAll();

// Get documents
$stmt = $db->prepare("
    SELECT sd.*, u.first_name, u.last_name
    FROM study_documents sd
    JOIN users u ON sd.uploaded_by = u.id
    WHERE sd.study_id = ?
    ORDER BY sd.created_at DESC
");
$stmt->execute([$studyId]);
$documents = $stmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $action = $_POST['action'] ?? 'update';
    
    if ($action === 'update') {
        $title = sanitize($_POST['title'] ?? '');
        $type = sanitize($_POST['type'] ?? '');
        $status = sanitize($_POST['status'] ?? 'draft');
        $summary = sanitize($_POST['summary'] ?? '');
        $objectives = sanitize($_POST['objectives'] ?? '');
        $methodology = sanitize($_POST['methodology'] ?? '');
        
        if (empty($title)) {
            $error = 'Study title is required.';
        } else {
            try {
                $stmt = $db->prepare("
                    UPDATE studies SET
                        title = ?, type = ?, status = ?, summary = ?,
                        objectives = ?, methodology = ?
                    WHERE id = ? AND creator_id = ?
                ");
                
                $stmt->execute([
                    $title, $type, $status, $summary,
                    $objectives, $methodology, $studyId, $userId
                ]);
                
                logActivity('study_updated', 'studies', $studyId);
                $success = 'Study updated successfully!';
                
                // Refresh study data
                $stmt = $db->prepare("SELECT * FROM studies WHERE id = ?");
                $stmt->execute([$studyId]);
                $study = $stmt->fetch();
                
            } catch (Exception $e) {
                $error = 'Failed to update study.';
            }
        }
    } elseif ($action === 'delete') {
        try {
            $stmt = $db->prepare("DELETE FROM studies WHERE id = ? AND creator_id = ?");
            $stmt->execute([$studyId, $userId]);
            
            logActivity('study_deleted', 'studies', $studyId);
            redirect(SITE_URL . '/researcher/studies.php');
            
        } catch (Exception $e) {
            $error = 'Failed to delete study.';
        }
    }
}

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-edit"></i> Edit Study</h1>
                <div class="btn-toolbar">
                    <a href="studies.php" class="btn btn-outline-secondary me-2">
                        <i class="fas fa-arrow-left"></i> Back
                    </a>
                    <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </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; ?>

            <ul class="nav nav-tabs mb-4" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" data-bs-toggle="tab" href="#details">
                        <i class="fas fa-info-circle"></i> Details
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#collaborators">
                        <i class="fas fa-users"></i> Collaborators (<?php echo count($collaborators); ?>)
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#documents">
                        <i class="fas fa-file"></i> Documents (<?php echo count($documents); ?>)
                    </a>
                </li>
            </ul>

            <div class="tab-content">
                <!-- Details Tab -->
                <div class="tab-pane fade show active" id="details">
                    <form method="POST" action="">
                        <?php echo csrfField(); ?>
                        <input type="hidden" name="action" value="update">

                        <div class="card shadow mb-4">
                            <div class="card-header">
                                <h5 class="mb-0">Study Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="title" class="form-label">Title *</label>
                                    <input type="text" class="form-control" id="title" name="title" 
                                           value="<?php echo e($study['title']); ?>" required>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="type" class="form-label">Type *</label>
                                        <select class="form-select" id="type" name="type" required>
                                            <option value="clinical" <?php echo $study['type'] === 'clinical' ? 'selected' : ''; ?>>Clinical</option>
                                            <option value="surgical" <?php echo $study['type'] === 'surgical' ? 'selected' : ''; ?>>Surgical</option>
                                            <option value="fertility" <?php echo $study['type'] === 'fertility' ? 'selected' : ''; ?>>Fertility</option>
                                            <option value="urogynecology" <?php echo $study['type'] === 'urogynecology' ? 'selected' : ''; ?>>Urogynecology</option>
                                            <option value="menopause" <?php echo $study['type'] === 'menopause' ? 'selected' : ''; ?>>Menopause</option>
                                            <option value="other" <?php echo $study['type'] === 'other' ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label for="status" class="form-label">Status *</label>
                                        <select class="form-select" id="status" name="status" required>
                                            <option value="draft" <?php echo $study['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                            <option value="active" <?php echo $study['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="completed" <?php echo $study['status'] === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                            <option value="archived" <?php echo $study['status'] === 'archived' ? 'selected' : ''; ?>>Archived</option>
                                        </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"><?php echo e($study['summary']); ?></textarea>
                                </div>

                                <div class="mb-3">
                                    <label for="objectives" class="form-label">Objectives</label>
                                    <textarea class="form-control" id="objectives" name="objectives" rows="4"><?php echo e($study['objectives']); ?></textarea>
                                </div>

                                <div class="mb-3">
                                    <label for="methodology" class="form-label">Methodology</label>
                                    <textarea class="form-control" id="methodology" name="methodology" rows="4"><?php echo e($study['methodology']); ?></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end mb-4">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Changes
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Collaborators Tab -->
                <div class="tab-pane fade" id="collaborators">
                    <div class="card shadow">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Collaborators</h5>
                            <button class="btn btn-sm btn-primary">
                                <i class="fas fa-plus"></i> Invite Collaborator
                            </button>
                        </div>
                        <div class="card-body">
                            <?php if (empty($collaborators)): ?>
                                <p class="text-muted text-center py-4">No collaborators yet.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table">
                                        <thead>
                                            <tr>
                                                <th>Name</th>
                                                <th>Role</th>
                                                <th>Status</th>
                                                <th>Joined</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($collaborators as $collab): ?>
                                            <tr>
                                                <td><?php echo e($collab['first_name'] . ' ' . $collab['last_name']); ?></td>
                                                <td><span class="badge bg-info"><?php echo ucfirst($collab['role']); ?></span></td>
                                                <td><span class="badge bg-<?php echo $collab['status'] === 'active' ? 'success' : 'warning'; ?>"><?php echo ucfirst($collab['status']); ?></span></td>
                                                <td><?php echo date('M d, Y', strtotime($collab['joined_at'])); ?></td>
                                                <td>
                                                    <button class="btn btn-sm btn-outline-danger">Remove</button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Documents Tab -->
                <div class="tab-pane fade" id="documents">
                    <div class="card shadow">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Documents</h5>
                            <button class="btn btn-sm btn-primary">
                                <i class="fas fa-upload"></i> Upload Document
                            </button>
                        </div>
                        <div class="card-body">
                            <?php if (empty($documents)): ?>
                                <p class="text-muted text-center py-4">No documents uploaded yet.</p>
                            <?php else: ?>
                                <div class="list-group">
                                    <?php foreach ($documents as $doc): ?>
                                    <div class="list-group-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="mb-1">
                                                    <i class="fas fa-file-<?php echo $doc['file_type'] === 'pdf' ? 'pdf' : 'alt'; ?>"></i>
                                                    <?php echo e($doc['title']); ?>
                                                </h6>
                                                <small class="text-muted">
                                                    Uploaded by <?php echo e($doc['first_name'] . ' ' . $doc['last_name']); ?> 
                                                    on <?php echo date('M d, Y', strtotime($doc['created_at'])); ?>
                                                </small>
                                            </div>
                                            <div>
                                                <a href="#" class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-download"></i> Download
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Study</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this study? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form method="POST" action="" style="display: inline;">
                    <?php echo csrfField(); ?>
                    <input type="hidden" name="action" value="delete">
                    <button type="submit" class="btn btn-danger">Delete Study</button>
                </form>
            </div>
        </div>
    </div>
</div>

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