<?php
/**
 * Edit Researcher Profile
 * OBGYN Research & Collaboration Platform
 */

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

// Check if user is logged in
requireLogin();

// Check if user is a researcher
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Edit Profile';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Get current profile data
$db = getDB();
$stmt = $db->prepare("
    SELECT rp.*, u.first_name, u.last_name, u.email
    FROM researcher_profiles rp
    JOIN users u ON rp.user_id = u.id
    WHERE rp.user_id = ?
");
$stmt->execute([$userId]);
$profile = $stmt->fetch();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    try {
        $db->beginTransaction();
        
        // Update user table
        $firstName = sanitize($_POST['first_name'] ?? '');
        $lastName = sanitize($_POST['last_name'] ?? '');
        
        if (empty($firstName) || empty($lastName)) {
            throw new Exception('First name and last name are required.');
        }
        
        $stmt = $db->prepare("UPDATE users SET first_name = ?, last_name = ? WHERE id = ?");
        $stmt->execute([$firstName, $lastName, $userId]);
        
        // Handle photo upload
        $photoPath = $profile['photo'];
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = UPLOADS_PATH . '/profiles/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileExtension = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array($fileExtension, $allowedExtensions)) {
                throw new Exception('Invalid file type. Only JPG, PNG, and GIF are allowed.');
            }
            
            if ($_FILES['photo']['size'] > 5242880) { // 5MB
                throw new Exception('File size must be less than 5MB.');
            }
            
            $newFileName = 'profile_' . $userId . '_' . time() . '.' . $fileExtension;
            $uploadPath = $uploadDir . $newFileName;
            
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadPath)) {
                // Delete old photo if exists
                if ($profile['photo'] && file_exists(UPLOADS_PATH . '/' . $profile['photo'])) {
                    unlink(UPLOADS_PATH . '/' . $profile['photo']);
                }
                $photoPath = 'profiles/' . $newFileName;
            }
        }
        
        // Update researcher profile
        $stmt = $db->prepare("
            UPDATE researcher_profiles SET
                photo = ?,
                title = ?,
                specialization = ?,
                institution_id = ?,
                department = ?,
                degrees = ?,
                bio = ?,
                research_interests = ?,
                orcid_id = ?,
                google_scholar = ?,
                researchgate = ?,
                linkedin = ?,
                phone = ?,
                phone_visible = ?,
                country = ?,
                city = ?
            WHERE user_id = ?
        ");
        
        $stmt->execute([
            $photoPath,
            sanitize($_POST['title'] ?? ''),
            sanitize($_POST['specialization'] ?? ''),
            !empty($_POST['institution_id']) ? intval($_POST['institution_id']) : null,
            sanitize($_POST['department'] ?? ''),
            sanitize($_POST['degrees'] ?? ''),
            sanitize($_POST['bio'] ?? ''),
            sanitize($_POST['research_interests'] ?? ''),
            sanitize($_POST['orcid_id'] ?? ''),
            sanitize($_POST['google_scholar'] ?? ''),
            sanitize($_POST['researchgate'] ?? ''),
            sanitize($_POST['linkedin'] ?? ''),
            sanitize($_POST['phone'] ?? ''),
            isset($_POST['phone_visible']) ? 1 : 0,
            sanitize($_POST['country'] ?? ''),
            sanitize($_POST['city'] ?? ''),
            $userId
        ]);
        
        $db->commit();
        
        // Log activity
        logActivity('profile_updated', 'researcher_profiles', $profile['id']);
        
        $success = 'Profile updated successfully!';
        
        // Refresh profile data
        $stmt = $db->prepare("
            SELECT rp.*, u.first_name, u.last_name, u.email
            FROM researcher_profiles rp
            JOIN users u ON rp.user_id = u.id
            WHERE rp.user_id = ?
        ");
        $stmt->execute([$userId]);
        $profile = $stmt->fetch();
        
    } catch (Exception $e) {
        $db->rollBack();
        $error = $e->getMessage();
    }
}

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

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav class="col-md-3 col-lg-2 d-md-block bg-light sidebar">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">
                            <i class="fas fa-home"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="profile.php">
                            <i class="fas fa-user"></i> My Profile
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="studies.php">
                            <i class="fas fa-flask"></i> My Studies
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="collaborations.php">
                            <i class="fas fa-users"></i> Collaborations
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="messages.php">
                            <i class="fas fa-envelope"></i> Messages
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="notifications.php">
                            <i class="fas fa-bell"></i> Notifications
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="settings.php">
                            <i class="fas fa-cog"></i> Settings
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Main content -->
        <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-user-edit"></i> Edit Profile
                </h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="profile.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Profile
                    </a>
                </div>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <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" role="alert">
                    <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; ?>

            <form method="POST" action="" enctype="multipart/form-data" class="needs-validation" novalidate>
                <?php echo csrfField(); ?>
                
                <div class="row">
                    <div class="col-lg-8">
                        <!-- Basic Information -->
                        <div class="card shadow mb-4">
                            <div class="card-header">
                                <h5 class="mb-0"><i class="fas fa-user"></i> Basic Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="first_name" class="form-label">First Name *</label>
                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                               value="<?php echo e($profile['first_name']); ?>" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="last_name" class="form-label">Last Name *</label>
                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                               value="<?php echo e($profile['last_name']); ?>" required>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="email" 
                                           value="<?php echo e($profile['email']); ?>" disabled>
                                    <small class="text-muted">Email cannot be changed here. Go to Settings to update.</small>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="title" class="form-label">Professional Title</label>
                                        <input type="text" class="form-control" id="title" name="title" 
                                               value="<?php echo e($profile['title'] ?? ''); ?>"
                                               placeholder="e.g., Dr., Prof., MD">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="specialization" class="form-label">Specialization</label>
                                        <input type="text" class="form-control" id="specialization" name="specialization" 
                                               value="<?php echo e($profile['specialization'] ?? ''); ?>"
                                               placeholder="e.g., Gynecologic Oncology">
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="bio" class="form-label">Bio</label>
                                    <textarea class="form-control" id="bio" name="bio" rows="4" 
                                              placeholder="Tell us about yourself..."><?php echo e($profile['bio'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="research_interests" class="form-label">Research Interests</label>
                                    <textarea class="form-control" id="research_interests" name="research_interests" rows="3" 
                                              placeholder="Describe your research interests..."><?php echo e($profile['research_interests'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="mb-Great! Now let me create **researcher/edit-profile.php**:

<create_file>
<path>d:/Coding/xampp/htdocs/obgyn-research-platform/researcher/edit-profile.php</path>
<content>
<?php
/**
 * Edit Researcher Profile
 * OBGYN Research & Collaboration Platform
 */

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

// Check if user is logged in
requireLogin();

// Check if user is a researcher
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Edit Profile';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Get current profile data
$db = getDB();
$stmt = $db->prepare("
    SELECT rp.*, u.first_name, u.last_name, u.email
    FROM researcher_profiles rp
    JOIN users u ON rp.user_id = u.id
    WHERE rp.user_id = ?
");
$stmt->execute([$userId]);
$profile = $stmt->fetch();

// Get institutions for dropdown
$stmt = $db->prepare("SELECT id, name, type, country FROM institutions ORDER BY name");
$stmt->execute();
$institutions = $stmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $data = [
        'first_name' => sanitize($_POST['first_name'] ?? ''),
        'last_name' => sanitize($_POST['last_name'] ?? ''),
        'title' => sanitize($_POST['title'] ?? ''),
        'specialization' => sanitize($_POST['specialization'] ?? ''),
        'institution_id' => !empty($_POST['institution_id']) ? (int)$_POST['institution_id'] : null,
        'department' => sanitize($_POST['department'] ?? ''),
        'degrees' => sanitize($_POST['degrees'] ?? ''),
        'bio' => sanitize($_POST['bio'] ?? ''),
        'research_interests' => sanitize($_POST['research_interests'] ?? ''),
        'orcid_id' => sanitize($_POST['orcid_id'] ?? ''),
        'google_scholar' => sanitize($_POST['google_scholar'] ?? ''),
        'researchgate' => sanitize($_POST['researchgate'] ?? ''),
        'linkedin' => sanitize($_POST['linkedin'] ?? ''),
        'phone' => sanitize($_POST['phone'] ?? ''),
        'phone_visible' => isset($_POST['phone_visible']) ? 1 : 0,
        'country' => sanitize($_POST['country'] ?? ''),
        'city' => sanitize($_POST['city'] ?? '')
    ];
    
    // Validate required fields
    if (empty($data['first_name']) || empty($data['last_name'])) {
        $error = 'First name and last name are required.';
    } elseif (!empty($data['orcid_id']) && !preg_match('/^\d{4}-\d{4}-\d{4}-\d{4}$/', $data['orcid_id'])) {
        $error = 'ORCID ID must be in format XXXX-XXXX-XXXX-XXXX.';
    } elseif (!empty($data['google_scholar']) && !filter_var($data['google_scholar'], FILTER_VALIDATE_URL)) {
        $error = 'Google Scholar URL must be a valid URL.';
    } elseif (!empty($data['researchgate']) && !filter_var($data['researchgate'], FILTER_VALIDATE_URL)) {
        $error = 'ResearchGate URL must be a valid URL.';
    } elseif (!empty($data['linkedin']) && !filter_var($data['linkedin'], FILTER_VALIDATE_URL)) {
        $error = 'LinkedIn URL must be a valid URL.';
    } else {
        // Handle photo upload
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $uploadResult = uploadFile($_FILES['photo'], 'profile_photos', ['jpg', 'jpeg', 'png', 'gif'], 2097152); // 2MB
            
            if ($uploadResult['success']) {
                $data['photo'] = $uploadResult['filename'];
                
                // Delete old photo if exists
                if ($profile['photo'] && file_exists(UPLOADS_PATH . '/' . $profile['photo'])) {
                    unlink(UPLOADS_PATH . '/' . $profile['photo']);
                }
            } else {
                $error = $uploadResult['message'];
            }
        }
        
        if (empty($error)) {
            try {
                // Update users table
                $stmt = $db->prepare("
                    UPDATE users 
                    SET first_name = ?, last_name = ? 
                    WHERE id = ?
                ");
                $stmt->execute([$data['first_name'], $data['last_name'], $userId]);
                
                // Update researcher_profiles table
                $stmt = $db->prepare("
                    UPDATE researcher_profiles 
                    SET title = ?, specialization = ?, institution_id = ?, department = ?, 
                        degrees = ?, bio = ?, research_interests = ?, orcid_id = ?, 
                        google_scholar = ?, researchgate = ?, linkedin = ?, 
                        phone = ?, phone_visible = ?, country = ?, city = ?" . 
                        (isset($data['photo']) ? ", photo = ?" : "") . "
                    WHERE user_id = ?
                ");
                
                $params = [
                    $data['title'], $data['specialization'], $data['institution_id'], $data['department'],
                    $data['degrees'], $data['bio'], $data['research_interests'], $data['orcid_id'],
                    $data['google_scholar'], $data['researchgate'], $data['linkedin'],
                    $data['phone'], $data['phone_visible'], $data['country'], $data['city']
                ];
                
                if (isset($data['photo'])) {
                    $params[] = $data['photo'];
                }
                
                $params[] = $userId;
                $stmt->execute($params);
                
                // Log activity
                logActivity('profile_updated', 'researcher_profiles', $userId);
                
                $success = 'Profile updated successfully!';
                
                // Refresh profile data
                $stmt = $db->prepare("
                    SELECT rp.*, u.first_name, u.last_name, u.email
                    FROM researcher_profiles rp
                    JOIN users u ON rp.user_id = u.id
                    WHERE rp.user_id = ?
                ");
                $stmt->execute([$userId]);
                $profile = $stmt->fetch();
                
            } catch (Exception $e) {
                error_log("Profile update error: " . $e->getMessage());
                $error = 'Failed to update profile. Please try again.';
            }
        }
    }
}

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

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav class="col-md-3 col-lg-2 d-md-block bg-light sidebar">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">
                            <i class="fas fa-home"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="profile.php">
                            <i class="fas fa-user"></i> My Profile
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="studies.php">
                            <i class="fas fa-flask"></i> My Studies
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="collaborations.php">
                            <i class="fas fa-users"></i> Collaborations
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="messages.php">
                            <i class="fas fa-envelope"></i> Messages
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="notifications.php">
                            <i class="fas fa-bell"></i> Notifications
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="settings.php">
                            <i class="fas fa-cog"></i> Settings
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Main content -->
        <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 Profile
                </h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="profile.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Profile
                    </a>
                </div>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <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" role="alert">
                    <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; ?>

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

                <div class="row">
                    <!-- Profile Photo -->
                    <div class="col-lg-4 mb-4">
                        <div class="card shadow">
                            <div class="card-header">
                                <h5 class="mb-0"><i class="fas fa-camera"></i> Profile Photo</h5>
                            </div>
                            <div class="card-body text-center">
                                <div id="photoPreview" class="mb-3">
                                    <?php if ($profile['photo']): ?>
                                        <img src="<?php echo UPLOADS_URL . '/' . e($profile['photo']); ?>" 
                                             alt="Current Photo" 
                                             class="rounded-circle" 
                                             style="width: 150px; height: 150px; object-fit: cover;">
                                    <?php else: ?>
                                        <div class="rounded-circle bg-primary text-white d-inline-flex align-items-center justify-content-center" 
                                             style="width: 150px; height: 150px; font-size: 3rem;">
                                            <?php echo strtoupper(substr($profile['first_name'], 0, 1) . substr($profile['last_name'], 0, 1)); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="mb-3">
                                    <input type="file" class="form-control" id="photo" name="photo" 
                                           accept="image/*" onchange="previewPhoto(this)">
                                    <small class="form-text text-muted">
                                        JPG, PNG, GIF up to 2MB
                                    </small>
                                </div>
                                
                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="removePhoto()">
                                    <i class="fas fa-trash"></i> Remove Photo
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Basic Information -->
                    <div class="col-lg-8 mb-4">
                        <div class="card shadow">
                            <div class="card-header">
                                <h5 class="mb-0"><i class="fas fa-user"></i> Basic Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="first_name" class="form-label">First Name *</label>
                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                               value="<?php echo e($profile['first_name']); ?>" required>
                                        <div class="invalid-feedback">First name is required.</div>
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="last_name" class="form-label">Last Name *</label>
                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                               value="<?php echo e($profile['last_name']); ?>" required>
                                        <div class="invalid-feedback">Last name is required.</div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="title" class="form-label">Professional Title</label>
                                        <input type="text" class="form-control" id="title" name="title" 
                                               value="<?php echo e($profile['title']); ?>" 
                                               placeholder="e.g., Professor, Dr., MD">
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="specialization" class="form-label">Specialization</label>
                                        <select class="form-select" id="specialization" name="specialization">
                                            <option value="">Select specialization...</option>
                                            <option value="Obstetrics" <?php echo $profile['specialization'] === 'Obstetrics' ? 'selected' : ''; ?>>Obstetrics</option>
                                            <option value="Gynecology" <?php echo $profile['specialization'] === 'Gynecology' ? 'selected' : ''; ?>>Gynecology</option>
                                            <option value="Maternal-Fetal Medicine" <?php echo $profile['specialization'] === 'Maternal-Fetal Medicine' ? 'selected' : ''; ?>>Maternal-Fetal Medicine</option>
                                            <option value="Reproductive Endocrinology" <?php echo $profile['specialization'] === 'Reproductive Endocrinology' ? 'selected' : ''; ?>>Reproductive Endocrinology</option>
                                            <option value="Urogynecology" <?php echo $profile['specialization'] === 'Urogynecology' ? 'selected' : ''; ?>>Urogynecology</option>
                                            <option value="Gynecologic Oncology" <?php echo $profile['specialization'] === 'Gynecologic Oncology' ? 'selected' : ''; ?>>Gynecologic Oncology</option>
                                            <option value="Other" <?php echo $profile['specialization'] === 'Other' ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="bio" class="form-label">Professional Bio</label>
                                    <textarea class="form-control" id="bio" name="bio" rows="4" 
                                              placeholder="Tell us about your professional background, experience, and expertise..."><?php echo e($profile['bio']); ?></textarea>
                                    <small class="form-text text-muted">Brief professional biography (optional)</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="research_interests" class="form-label">Research Interests</label>
                                    <textarea class="form-control" id="research_interests" name="research_interests" rows="3" 
                                              placeholder="Describe your research interests and focus areas..."><?php echo e($profile['research_interests']); ?></textarea>
                                    <small class="form-text text-muted">Areas of research interest (optional)</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="degrees" class="form-label">Education & Degrees</label>
                                    <textarea class="form-control" id="degrees" name="degrees" rows="3" 
                                              placeholder="List your educational background and degrees..."><?php echo e($profile['degrees']); ?></textarea>
                                    <small class="form-text text-muted">Educational qualifications and degrees (optional)</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Institution & Location -->
                <div class="card shadow mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-university"></i> Institution & Location</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 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 $profile['institution_id'] == $inst['id'] ? 'selected' : ''; ?>>
                                            <?php echo e($inst['name']); ?> 
                                            <small class="text-muted">(<?php echo e($inst['country']); ?>)</small>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="form-text text-muted">Your affiliated institution (optional)</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="department" class="form-label">Department</label>
                                <input type="text" class="form-control" id="department" name="department" 
                                       value="<?php echo e($profile['department']); ?>" 
                                       placeholder="e.g., Department of Obstetrics and Gynecology">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="country" class="form-label">Country</label>
                                <select class="form-select" id="country" name="country">
                                    <option value="">Select country...</option>
                                    <option value="United States" <?php echo $profile['country'] === 'United States' ? 'selected' : ''; ?>>United States</option>
                                    <option value="United Kingdom" <?php echo $profile['country'] === 'United Kingdom' ? 'selected' : ''; ?>>United Kingdom</option>
                                    <option value="Canada" <?php echo $profile['country'] === 'Canada' ? 'selected' : ''; ?>>Canada</option>
                                    <option value="Australia" <?php echo $profile['country'] === 'Australia' ? 'selected' : ''; ?>>Australia</option>
                                    <option value="Germany" <?php echo $profile['country'] === 'Germany' ? 'selected' : ''; ?>>Germany</option>
                                    <option value="France" <?php echo $profile['country'] === 'France' ? 'selected' : ''; ?>>France</option>
                                    <option value="Japan" <?php echo $profile['country'] === 'Japan' ? 'selected' : ''; ?>>Japan</option>
                                    <option value="Other" <?php echo $profile['country'] === 'Other' ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="city" class="form-label">City</label>
                                <input type="text" class="form-control" id="city" name="city" 
                                       value="<?php echo e($profile['city']); ?>" 
                                       placeholder="City name">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Contact & Social Links -->
                <div class="card shadow mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-address-book"></i> Contact & Social Links</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="phone" class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       value="<?php echo e($profile['phone']); ?>" 
                                       placeholder="+1 (555) 123-4567">
                            </div>
                            
                            <div class="col-md-6 mb-3 d-flex align-items-end">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="phone_visible" name="phone_visible" 
                                           <?php echo $profile['phone_visible'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="phone_visible">
                                        Make phone number visible to other researchers
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="orcid_id" class="form-label">ORCID ID</label>
                                <input type="text" class="form-control" id="orcid_id" name="orcid_id" 
                                       value="<?php echo e($profile['orcid_id']); ?>" 
                                       placeholder="0000-0000-0000-0000" 
                                       pattern="\d{4}-\d{4}-\d{4}-\d{4}">
                                <small class="form-text text-muted">Format: XXXX-XXXX-XXXX-XXXX</small>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="google_scholar" class="form-label">Google Scholar URL</label>
                                <input type="url" class="form-control" id="google_scholar" name="google_scholar" 
                                       value="<?php echo e($profile['google_scholar']); ?>" 
                                       placeholder="https://scholar.google.com/...">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="researchgate" class="form-label">ResearchGate URL</label>
                                <input type="url" class="form-control" id="researchgate" name="researchgate" 
                                       value="<?php echo e($profile['researchgate']); ?>" 
                                       placeholder="https://www.researchgate.net/...">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="linkedin" class="form-label">LinkedIn URL</label>
                                <input type="url" class="form-control" id="linkedin" name="linkedin" 
                                       value="<?php echo e($profile['linkedin']); ?>" 
                                       placeholder="https://www.linkedin.com/...">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Submit Buttons -->
                <div class="d-flex justify-content-between mb-4">
                    <a href="profile.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> Cancel
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save Changes
                    </button>
                </div>
            </form>
        </main>
    </div>
</div>

<script>
// Photo preview
function previewPhoto(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('photoPreview');
            preview.innerHTML = `<img src="${e.target.result}" alt="Preview" class="rounded-circle" style="width: 150px; height: 150px; object-fit: cover;">`;
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Remove photo
function removePhoto() {
    document.getElementById('photo').value = '';
    const preview = document.getElementById('photoPreview');
    preview.innerHTML = `<div class="rounded-circle bg-primary text-white d-inline-flex align-items-center justify-content-center" 
                           style="width: 150px; height: 150px; font-size: 3rem;">
                           <?php echo strtoupper(substr($profile['first_name'], 0, 1) . substr($profile['last_name'], 0, 1)); ?>
                        </div>`;
}

// ORCID ID formatting
document.getElementById('orcid_id').addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length >= 4) value = value.substring(0, 4) + '-' + value.substring(4);
    if (value.length >= 9) value = value.substring(0, 9) + '-' + value.substring(9);
    if (value.length >= 14) value = value.substring(0, 14) + '-' + value.substring(14);
    if (value.length > 19) value = value.substring(0, 19);
    e.target.value = value;
});
</script>

<style>
.sidebar {
    position: fixed;
    top: 56px;
    bottom: 0;
    left: 0;
    z-index: 100;
    padding: 0;
    box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
    overflow-y: auto;
}

.sidebar .nav-link {
    font-weight: 500;
    color: #333;
    padding: 0.75rem 1rem;
}

.sidebar .nav-link:hover {
    background-color: #f8f9fa;
}

.sidebar .nav-link.active {
    color: #007bff;
    background-color: #e7f3ff;
    border-left: 3px solid #007bff;
}

.sidebar .nav-link i {
    margin-right: 0.5rem;
}

main {
    margin-top: 56px;
}
</style>

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