<?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/researcher-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <?php include 'sidebar.php'; ?>

        <!-- 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 SITE_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>

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