<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2 class="fw-bold font-outfit text-dark m-0">Edit Profile</h2>
                    <p class="text-muted mb-0">Update your credentials and account details.</p>
                </div>
                <a href="<?= APP_URL ?>/profile" class="btn btn-outline-secondary rounded-pill px-4"><i class="fa-solid fa-arrow-left me-2"></i>Back to Profile</a>
            </div>

            <div class="row g-4">
                <!-- Avatar Upload Section -->
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm p-4 text-center">
                        <h5 class="fw-bold font-outfit mb-3">Profile Photo</h5>
                        <div class="position-relative d-inline-block mx-auto mb-3" id="avatar-container">
                            <img src="<?= avatarUrl($user['avatar'], $user['first_name'] . ' ' . $user['last_name']) ?>" id="avatar-preview" alt="Avatar" class="rounded-circle border border-4 border-white shadow" style="width: 130px; height: 130px; object-fit: cover;">
                            <label for="avatar-input" class="btn btn-primary btn-sm position-absolute bottom-0 end-0 rounded-circle p-2 shadow" style="width: 36px; height: 36px; cursor: pointer;">
                                <i class="fa-solid fa-camera"></i>
                            </label>
                            <input type="file" id="avatar-input" class="d-none" accept="image/*">
                        </div>
                        <p class="text-xs text-muted">Click the camera icon to upload a square JPG or PNG. Max size 5MB.</p>
                        <div id="upload-status" class="alert alert-success text-xs py-1 px-2 mt-2" style="display: none;"></div>
                    </div>
                </div>

                <!-- Form Section -->
                <div class="col-md-8">
                    <div class="card border-0 shadow-sm p-4">
                        <form action="<?= APP_URL ?>/profile/edit" method="POST">
                            <?= csrf_field() ?>

                            <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">Basic Info</h5>
                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label for="first_name" class="form-label text-sm fw-medium">First Name</label>
                                    <input type="text" class="form-control rounded-3" id="first_name" name="first_name" value="<?= htmlspecialchars($user['first_name']) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="last_name" class="form-label text-sm fw-medium">Last Name</label>
                                    <input type="text" class="form-control rounded-3" id="last_name" name="last_name" value="<?= htmlspecialchars($user['last_name']) ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="email" class="form-label text-sm fw-medium">Email Address</label>
                                    <input type="email" class="form-control rounded-3 bg-light" id="email" value="<?= htmlspecialchars($user['email']) ?>" readonly disabled>
                                    <small class="text-xs text-muted">Email address cannot be changed.</small>
                                </div>
                                <div class="col-md-6">
                                    <label for="phone" class="form-label text-sm fw-medium">Phone Number</label>
                                    <input type="tel" class="form-control rounded-3" id="phone" name="phone" value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
                                </div>
                            </div>

                            <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">Biography & Background</h5>
                            <div class="mb-4">
                                <label for="bio" class="form-label text-sm fw-medium">About You / Biography</label>
                                <textarea class="form-control rounded-3" id="bio" name="bio" rows="4" placeholder="Brief details about yourself..."><?= htmlspecialchars($profile['bio'] ?? '') ?></textarea>
                            </div>

                            <!-- Role-Specific Fields -->
                            <?php if (Auth::isStudent()): ?>
                                <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">High School (SHS) Information</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <label for="shs_school" class="form-label text-sm fw-medium">SHS Attended</label>
                                        <input type="text" class="form-control rounded-3" id="shs_school" name="shs_school" value="<?= htmlspecialchars($profile['shs_school'] ?? '') ?>" placeholder="e.g. Achimota School">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="shs_program" class="form-label text-sm fw-medium">SHS Academic Program</label>
                                        <select class="form-select rounded-3" id="shs_program" name="shs_program">
                                            <option value="">-- Select Program --</option>
                                            <option value="general_science" <?= ($profile['shs_program'] ?? '') === 'general_science' ? 'selected' : '' ?>>General Science</option>
                                            <option value="general_arts" <?= ($profile['shs_program'] ?? '') === 'general_arts' ? 'selected' : '' ?>>General Arts</option>
                                            <option value="business" <?= ($profile['shs_program'] ?? '') === 'business' ? 'selected' : '' ?>>Business</option>
                                            <option value="vocational" <?= ($profile['shs_program'] ?? '') === 'vocational' ? 'selected' : '' ?>>Vocational / Home Economics</option>
                                            <option value="visual_arts" <?= ($profile['shs_program'] ?? '') === 'visual_arts' ? 'selected' : '' ?>>Visual Arts</option>
                                            <option value="agricultural" <?= ($profile['shs_program'] ?? '') === 'agricultural' ? 'selected' : '' ?>>Agricultural Science</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="graduation_year" class="form-label text-sm fw-medium">Graduation Year</label>
                                        <input type="number" class="form-control rounded-3" id="graduation_year" name="graduation_year" value="<?= htmlspecialchars($profile['graduation_year'] ?? '') ?>" placeholder="e.g. 2026" min="2010" max="2035">
                                    </div>
                                </div>

                                <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">University Aspirations</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <label for="intended_program" class="form-label text-sm fw-medium">Intended Program</label>
                                        <input type="text" class="form-control rounded-3" id="intended_program" name="intended_program" value="<?= htmlspecialchars($profile['intended_program'] ?? '') ?>" placeholder="e.g. BSc Computer Engineering">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="preferred_university" class="form-label text-sm fw-medium">Preferred University</label>
                                        <input type="text" class="form-control rounded-3" id="preferred_university" name="preferred_university" value="<?= htmlspecialchars($profile['preferred_university'] ?? '') ?>" placeholder="e.g. KNUST">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="career_interests" class="form-label text-sm fw-medium">Career Interests</label>
                                        <input type="text" class="form-control rounded-3" id="career_interests" name="career_interests" value="<?= htmlspecialchars($profile['career_interests'] ?? '') ?>" placeholder="e.g. Software Engineer, Doctor">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="academic_strengths" class="form-label text-sm fw-medium">Academic Strengths</label>
                                        <input type="text" class="form-control rounded-3" id="academic_strengths" name="academic_strengths" value="<?= htmlspecialchars($profile['academic_strengths'] ?? '') ?>" placeholder="e.g. Mathematics, Elective Physics">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="financial_need" class="form-label text-sm fw-medium">Financial Need Status</label>
                                        <select class="form-select rounded-3" id="financial_need" name="financial_need">
                                            <option value="none" <?= ($profile['financial_need'] ?? '') === 'none' ? 'selected' : '' ?>>None (Fully Funded self-sponsor)</option>
                                            <option value="low" <?= ($profile['financial_need'] ?? '') === 'low' ? 'selected' : '' ?>>Low</option>
                                            <option value="moderate" <?= ($profile['financial_need'] ?? '') === 'moderate' ? 'selected' : '' ?>>Moderate</option>
                                            <option value="high" <?= ($profile['financial_need'] ?? '') === 'high' ? 'selected' : '' ?>>High (Requires Scholarship Support)</option>
                                        </select>
                                    </div>
                                </div>

                                <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">Personal Background</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <label for="date_of_birth" class="form-label text-sm fw-medium">Date of Birth</label>
                                        <input type="date" class="form-control rounded-3" id="date_of_birth" name="date_of_birth" value="<?= htmlspecialchars($profile['date_of_birth'] ?? '') ?>">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="gender" class="form-label text-sm fw-medium">Gender</label>
                                        <select class="form-select rounded-3" id="gender" name="gender">
                                            <option value="">-- Select Gender --</option>
                                            <option value="male" <?= ($profile['gender'] ?? '') === 'male' ? 'selected' : '' ?>>Male</option>
                                            <option value="female" <?= ($profile['gender'] ?? '') === 'female' ? 'selected' : '' ?>>Female</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="country_id" class="form-label text-sm fw-medium">Country</label>
                                        <select class="form-select rounded-3" id="country_id" name="country_id">
                                            <?php foreach ($countries as $c): ?>
                                                <option value="<?= $c['id'] ?>" <?= ($profile['country_id'] ?? 1) == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="region_id" class="form-label text-sm fw-medium">Region (Ghana Only)</label>
                                        <select class="form-select rounded-3" id="region_id" name="region_id">
                                            <option value="">-- Select Region --</option>
                                            <?php foreach ($regions as $r): ?>
                                                <option value="<?= $r['id'] ?>" <?= ($profile['region_id'] ?? '') == $r['id'] ? 'selected' : '' ?>><?= htmlspecialchars($r['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="city" class="form-label text-sm fw-medium">City</label>
                                        <input type="text" class="form-control rounded-3" id="city" name="city" value="<?= htmlspecialchars($profile['city'] ?? '') ?>">
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if (Auth::isMentor()): ?>
                                <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">University Affiliation</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <label for="university_id" class="form-label text-sm fw-medium">My University</label>
                                        <select class="form-select rounded-3" id="university_id" name="university_id">
                                            <option value="">-- Select University --</option>
                                            <?php foreach ($universities as $uni): ?>
                                                <option value="<?= $uni['id'] ?>" <?= ($profile['university_id'] ?? '') == $uni['id'] ? 'selected' : '' ?>><?= htmlspecialchars($uni['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="program" class="form-label text-sm fw-medium">Program of Study</label>
                                        <input type="text" class="form-control rounded-3" id="program" name="program" value="<?= htmlspecialchars($profile['program'] ?? '') ?>" placeholder="e.g. BSc Computer Science">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="faculty" class="form-label text-sm fw-medium">Faculty / College</label>
                                        <input type="text" class="form-control rounded-3" id="faculty" name="faculty" value="<?= htmlspecialchars($profile['faculty'] ?? '') ?>" placeholder="e.g. College of Science">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="year_level" class="form-label text-sm fw-medium">Year Level</label>
                                        <select class="form-select rounded-3" id="year_level" name="year_level">
                                            <option value="">-- Select Year --</option>
                                            <option value="1" <?= ($profile['year_level'] ?? '') == 1 ? 'selected' : '' ?>>First Year (Level 100)</option>
                                            <option value="2" <?= ($profile['year_level'] ?? '') == 2 ? 'selected' : '' ?>>Second Year (Level 200)</option>
                                            <option value="3" <?= ($profile['year_level'] ?? '') == 3 ? 'selected' : '' ?>>Third Year (Level 300)</option>
                                            <option value="4" <?= ($profile['year_level'] ?? '') == 4 ? 'selected' : '' ?>>Fourth Year (Level 400)</option>
                                            <option value="postgrad" <?= ($profile['year_level'] ?? '') === 'postgrad' ? 'selected' : '' ?>>Postgraduate</option>
                                            <option value="alumni" <?= ($profile['year_level'] ?? '') === 'alumni' ? 'selected' : '' ?>>Alumnus / Professional</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="max_mentees" class="form-label text-sm fw-medium">Max Mentees Limit</label>
                                        <input type="number" class="form-control rounded-3" id="max_mentees" name="max_mentees" value="<?= htmlspecialchars($profile['max_mentees'] ?? 5) ?>" min="1" max="15">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="linkedin_url" class="form-label text-sm fw-medium">LinkedIn Profile URL</label>
                                        <input type="url" class="form-control rounded-3" id="linkedin_url" name="linkedin_url" value="<?= htmlspecialchars($profile['linkedin_url'] ?? '') ?>" placeholder="https://linkedin.com/in/username">
                                    </div>
                                    <div class="col-12">
                                        <label for="expertise_areas" class="form-label text-sm fw-medium">Expertise Areas / Tags</label>
                                        <input type="text" class="form-control rounded-3" id="expertise_areas" name="expertise_areas" value="<?= htmlspecialchars($profile['expertise_areas'] ?? '') ?>" placeholder="e.g. Programming, Calculus, Scholarship Writing">
                                    </div>
                                    <div class="col-12">
                                        <label for="career_goals" class="form-label text-sm fw-medium">Career Goals / Professional Path</label>
                                        <input type="text" class="form-control rounded-3" id="career_goals" name="career_goals" value="<?= htmlspecialchars($profile['career_goals'] ?? '') ?>">
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if (Auth::isTutor()): ?>
                                <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2">Academic Tutor Profile</h5>
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <label for="specializations" class="form-label text-sm fw-medium">Specializations</label>
                                        <input type="text" class="form-control rounded-3" id="specializations" name="specializations" value="<?= htmlspecialchars($profile['specializations'] ?? '') ?>" placeholder="e.g. Mathematics, Science">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="subjects" class="form-label text-sm fw-medium">Tutoring Subjects</label>
                                        <input type="text" class="form-control rounded-3" id="subjects" name="subjects" value="<?= htmlspecialchars($profile['subjects'] ?? '') ?>" placeholder="e.g. College Algebra, Physics 101">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="qualification" class="form-label text-sm fw-medium">Highest Qualification</label>
                                        <input type="text" class="form-control rounded-3" id="qualification" name="qualification" value="<?= htmlspecialchars($profile['qualification'] ?? '') ?>" placeholder="e.g. Bachelor of Education">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="institution" class="form-label text-sm fw-medium">Affiliation Institution</label>
                                        <input type="text" class="form-control rounded-3" id="institution" name="institution" value="<?= htmlspecialchars($profile['institution'] ?? '') ?>" placeholder="e.g. University of Cape Coast">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="hourly_rate" class="form-label text-sm fw-medium">Hourly Rate (GHS) (Optional)</label>
                                        <input type="number" class="form-control rounded-3" id="hourly_rate" name="hourly_rate" value="<?= htmlspecialchars($profile['hourly_rate'] ?? '') ?>" placeholder="e.g. 50">
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if (Auth::isMentor() || Auth::isTutor()): ?>
                                <h5 class="fw-bold font-outfit text-dark mb-3 border-bottom pb-2 mt-4">Weekly Availability Schedule</h5>
                                <p class="text-muted text-sm mb-3">Set your typical weekly schedule. Leave start/end times blank if you are unavailable on a specific day.</p>
                                <div class="row g-3 mb-4">
                                    <?php 
                                    $days = ['0' => 'Sunday', '1' => 'Monday', '2' => 'Tuesday', '3' => 'Wednesday', '4' => 'Thursday', '5' => 'Friday', '6' => 'Saturday'];
                                    foreach ($days as $idx => $dayName): 
                                        $dayBlocks = [];
                                        if (isset($availability) && is_array($availability)) {
                                            foreach ($availability as $avail) {
                                                if ($avail['day_of_week'] == $idx) {
                                                    $dayBlocks[] = [
                                                        'start' => substr($avail['start_time'], 0, 5),
                                                        'end' => substr($avail['end_time'], 0, 5)
                                                    ];
                                                }
                                            }
                                        }
                                        if (empty($dayBlocks)) {
                                            $dayBlocks[] = ['start' => '', 'end' => ''];
                                        }
                                    ?>
                                    <div class="col-12 border rounded-3 p-3 mb-2 bg-light day-container" data-day="<?= $idx ?>">
                                        <div class="d-flex align-items-start">
                                            <div class="fw-bold font-outfit pt-2" style="width: 100px;"><?= $dayName ?></div>
                                            <div class="flex-grow-1 blocks-container">
                                                <?php foreach ($dayBlocks as $bIdx => $block): ?>
                                                <div class="d-flex gap-3 align-items-center mb-2 time-block">
                                                    <div class="d-flex align-items-center gap-2">
                                                        <label class="text-muted text-xs mb-0">From</label>
                                                        <input type="time" name="availability[<?= $idx ?>][start][]" class="form-control form-control-sm" value="<?= htmlspecialchars($block['start']) ?>">
                                                    </div>
                                                    <div class="d-flex align-items-center gap-2">
                                                        <label class="text-muted text-xs mb-0">To</label>
                                                        <input type="time" name="availability[<?= $idx ?>][end][]" class="form-control form-control-sm" value="<?= htmlspecialchars($block['end']) ?>">
                                                    </div>
                                                    <button type="button" class="btn btn-sm btn-outline-danger remove-block ms-auto" <?= count($dayBlocks) === 1 && $block['start'] === '' ? 'style="display:none;"' : '' ?>><i class="fa-solid fa-trash"></i></button>
                                                </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <div class="ms-auto ps-5 pt-1">
                                            <button type="button" class="btn btn-sm btn-link text-decoration-none add-block" style="margin-left: 55px;"><i class="fa-solid fa-plus me-1"></i> Add Time Block</button>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>

                            <div class="mt-4 pt-3 border-top d-flex gap-2">
                                <button type="submit" class="btn btn-primary rounded-pill px-5 shadow-sm font-outfit fw-bold">Save Changes</button>
                                <a href="<?= APP_URL ?>/profile" class="btn btn-outline-secondary rounded-pill px-4">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const avatarInput = document.getElementById('avatar-input');
    const avatarPreview = document.getElementById('avatar-preview');
    const uploadStatus = document.getElementById('upload-status');

    if (avatarInput) {
        avatarInput.addEventListener('change', function() {
            if (!this.files.length) return;
            const file = this.files[0];
            const formData = new FormData();
            formData.append('avatar', file);

            uploadStatus.style.display = 'block';
            uploadStatus.className = 'alert alert-info text-xs py-1 px-2 mt-2';
            uploadStatus.textContent = 'Uploading...';

            fetch(APP_URL + '/profile/avatar', {
                method: 'POST',
                headers: {
                    'X-CSRF-Token': CSRF_TOKEN,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    avatarPreview.src = data.avatar_url;
                    // Also update header and sidebar avatars
                    const topAvatar = document.querySelector('.avatar-sm');
                    const sidebarAvatar = document.querySelector('.quick-avatar');
                    if (topAvatar) topAvatar.src = data.avatar_url;
                    if (sidebarAvatar) sidebarAvatar.src = data.avatar_url;

                    uploadStatus.className = 'alert alert-success text-xs py-1 px-2 mt-2';
                    uploadStatus.textContent = 'Avatar uploaded successfully!';
                    setTimeout(() => uploadStatus.style.display = 'none', 3000);
                } else {
                    uploadStatus.className = 'alert alert-danger text-xs py-1 px-2 mt-2';
                    uploadStatus.textContent = data.message;
                }
            })
            .catch(err => {
                uploadStatus.className = 'alert alert-danger text-xs py-1 px-2 mt-2';
                uploadStatus.textContent = 'An error occurred during upload.';
                console.error(err);
            });
        });
    }

    // Availability Time Blocks Logic
    document.querySelectorAll('.add-block').forEach(btn => {
        btn.addEventListener('click', function() {
            const container = this.closest('.day-container').querySelector('.blocks-container');
            const dayIdx = this.closest('.day-container').dataset.day;
            const blockHtml = `
                <div class="d-flex gap-3 align-items-center mb-2 time-block">
                    <div class="d-flex align-items-center gap-2">
                        <label class="text-muted text-xs mb-0">From</label>
                        <input type="time" name="availability[${dayIdx}][start][]" class="form-control form-control-sm" value="">
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <label class="text-muted text-xs mb-0">To</label>
                        <input type="time" name="availability[${dayIdx}][end][]" class="form-control form-control-sm" value="">
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-danger remove-block ms-auto"><i class="fa-solid fa-trash"></i></button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', blockHtml);
            
            // Show all remove buttons in this container
            container.querySelectorAll('.remove-block').forEach(b => b.style.display = 'block');
        });
    });

    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-block')) {
            const block = e.target.closest('.time-block');
            const container = block.closest('.blocks-container');
            
            if (container.querySelectorAll('.time-block').length > 1) {
                block.remove();
            } else {
                // If it's the last one, just clear the inputs and hide the button
                block.querySelectorAll('input').forEach(i => i.value = '');
                block.querySelector('.remove-block').style.display = 'none';
            }
        }
    });
});
</script>
