<?php
define('SECURE_ACCESS', true);

$pageTitle = "My Profile";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Auth check BEFORE header to prevent unauthenticated users from triggering DB queries
requireLogin();

// NOTE: Profile schema migrations (headline, location, about_summary, skills, 
// user_experiences, user_educations) are now handled in install.php/setup.php.
// Removed per-request ALTER TABLE checks for performance (#16).

require_once __DIR__ . '/../includes/header.php';

$user_id = $currentUser['id'];
$role = $currentUser['role'];
$error = '';
$success = '';

// Create uploads directory if it doesn't exist
$upload_dir = __DIR__ . '/uploads/profiles';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: profile");
        exit();
    }
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        
        if ($action === 'change_password') {
            $current_password = $_POST['current_password'] ?? '';
            $new_password = $_POST['new_password'] ?? '';
            $confirm_password = $_POST['confirm_password'] ?? '';
            
            if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
                $error = "All password fields are required.";
            } elseif ($new_password !== $confirm_password) {
                $error = "New password and confirmation password do not match.";
            } elseif (strlen($new_password) < 6) {
                $error = "New password must be at least 6 characters long.";
            } else {
                $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $hash = $stmt->fetchColumn();
                
                if (!password_verify($current_password, $hash)) {
                    $error = "Current password is incorrect.";
                } else {
                    $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt_update = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                    $stmt_update->execute([$new_hash, $user_id]);
                    $success = "Password successfully changed.";
                }
            }
        } elseif ($action === 'update_profile') {
            $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
            $first_name = htmlspecialchars(trim($_POST['first_name'] ?? ''), ENT_QUOTES, 'UTF-8');
            $last_name = htmlspecialchars(trim($_POST['last_name'] ?? ''), ENT_QUOTES, 'UTF-8');
            $headline = htmlspecialchars(trim($_POST['headline'] ?? ''), ENT_QUOTES, 'UTF-8');
            $location = htmlspecialchars(trim($_POST['location'] ?? ''), ENT_QUOTES, 'UTF-8');
            $about = htmlspecialchars(trim($_POST['about_summary'] ?? ''), ENT_QUOTES, 'UTF-8');
            $skills = htmlspecialchars(trim($_POST['skills'] ?? ''), ENT_QUOTES, 'UTF-8');
            
            if (empty($email) || empty($first_name) || empty($last_name)) {
                $error = "Email, First Name, and Last Name cannot be empty.";
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = "Please provide a valid email address.";
            } else {
                    // Check if email already exists for another user
                    $check_email = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
                    $check_email->execute([$email, $user_id]);
                    if ($check_email->fetchColumn() > 0) {
                        $error = "This email address is already in use by another account.";
                    } else {
                        $profile_picture_url = $_POST['existing_profile_picture'] ?? '';
                        $banner_picture_url = $_POST['existing_banner_picture'] ?? '';
                        
                        // Secure upload helper
                        function processImageUpload($fileInputName, $upload_dir, $prefix, $user_id) {
                            if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] === UPLOAD_ERR_OK) {
                                $tmp_name = $_FILES[$fileInputName]['tmp_name'];
                                $original_name = $_FILES[$fileInputName]['name'];
                                $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
                                
                                $allowed_exts = ['jpg', 'jpeg', 'png'];
                                if (!in_array($ext, $allowed_exts)) return false;
                                
                                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                                $mime = finfo_file($finfo, $tmp_name);
                                finfo_close($finfo);
                                
                                $allowed_mimes = ['image/jpeg', 'image/png'];
                                if (!in_array($mime, $allowed_mimes)) return false;
                                
                                $filename = $prefix . '_' . $user_id . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
                                if (move_uploaded_file($tmp_name, $upload_dir . '/' . $filename)) {
                                    return 'uploads/profiles/' . $filename;
                                }
                            }
                            return false;
                        }

                        $uploaded_avatar = processImageUpload('profile_picture', $upload_dir, 'avatar', $user_id);
                        if ($uploaded_avatar) $profile_picture_url = $uploaded_avatar;

                        $uploaded_banner = processImageUpload('banner_picture', $upload_dir, 'banner', $user_id);
                        if ($uploaded_banner) $banner_picture_url = $uploaded_banner;

                        $stmt = $pdo->prepare("UPDATE users SET email = ?, first_name = ?, last_name = ?, headline = ?, location = ?, about_summary = ?, skills = ?, profile_picture_url = ?, banner_picture_url = ? WHERE id = ?");
                        $stmt->execute([$email, $first_name, $last_name, $headline, $location, $about, $skills, $profile_picture_url, $banner_picture_url, $user_id]);
                        $_SESSION['email'] = $email;
                        
                        $success = "Profile updated successfully.";
                    }
            }
        } elseif ($action === 'add_experience') {
            $title = trim($_POST['title'] ?? '');
            $company = trim($_POST['company'] ?? '');
            $location = trim($_POST['location'] ?? '');
            $start_date = $_POST['start_date'] ?? '';
            $end_date = $_POST['end_date'] ?? null;
            $is_current = isset($_POST['is_current']) ? 1 : 0;
            $description = trim($_POST['description'] ?? '');
            
            if (empty($end_date) || $is_current) $end_date = null;
            
            if (!empty($title) && !empty($company) && !empty($start_date)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO user_experiences (user_id, title, company, location, start_date, end_date, is_current, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $title, $company, $location, $start_date, $end_date, $is_current, $description]);
                    $success = "Experience added.";
                } catch (PDOException $e) {
                    $error = "Error adding experience: " . $e->getMessage();
                }
            } else {
                $error = "Title, Company, and Start Date are required.";
            }
        } elseif ($action === 'add_education') {
            $school = trim($_POST['school'] ?? '');
            $degree = trim($_POST['degree'] ?? '');
            $field = trim($_POST['field_of_study'] ?? '');
            $start_date = $_POST['start_date'] ?? null;
            $end_date = $_POST['end_date'] ?? null;
            $description = trim($_POST['description'] ?? '');
            
            if (empty($start_date)) $start_date = null;
            if (empty($end_date)) $end_date = null;
            
            if (!empty($school)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO user_educations (user_id, school, degree, field_of_study, start_date, end_date, description) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $school, $degree, $field, $start_date, $end_date, $description]);
                    $success = "Education added.";
                } catch (PDOException $e) {
                    $error = "Error adding education: " . $e->getMessage();
                }
            } else {
                $error = "School is required.";
            }
        } elseif ($action === 'delete_exp') {
            $id = (int)($_POST['id'] ?? 0);
            $pdo->prepare("DELETE FROM user_experiences WHERE id = ? AND user_id = ?")->execute([$id, $user_id]);
            $success = "Experience removed.";
        } elseif ($action === 'delete_edu') {
            $id = (int)($_POST['id'] ?? 0);
            $pdo->prepare("DELETE FROM user_educations WHERE id = ? AND user_id = ?")->execute([$id, $user_id]);
            $success = "Education removed.";
        } elseif ($action === 'update_role') {
            // Update specific profile
            if ($role === 'speaker') {
                $full_name = trim($_POST['full_name'] ?? '');
                $bio = trim($_POST['bio'] ?? '');
                $expertise = trim($_POST['expertise'] ?? '');
                $organization = trim($_POST['organization'] ?? '');
                
                $check = $pdo->prepare("SELECT COUNT(*) FROM speaker_profiles WHERE user_id = ?");
                $check->execute([$user_id]);
                if ($check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO speaker_profiles (user_id, full_name, bio, expertise, organization) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $full_name, $bio, $expertise, $organization]);
                } else {
                    $stmt = $pdo->prepare("UPDATE speaker_profiles SET full_name = ?, bio = ?, expertise = ?, organization = ? WHERE user_id = ?");
                    $stmt->execute([$full_name, $bio, $expertise, $organization, $user_id]);
                }
            } elseif ($role === 'organizer') {
                $full_name = trim($_POST['full_name'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $company = trim($_POST['company'] ?? '');
                $department = trim($_POST['department'] ?? '');
                
                $check = $pdo->prepare("SELECT COUNT(*) FROM organizer_profiles WHERE user_id = ?");
                $check->execute([$user_id]);
                if ($check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO organizer_profiles (user_id, full_name, phone, company, department) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $full_name, $phone, $company, $department]);
                } else {
                    $stmt = $pdo->prepare("UPDATE organizer_profiles SET full_name = ?, phone = ?, company = ?, department = ? WHERE user_id = ?");
                    $stmt->execute([$full_name, $phone, $company, $department, $user_id]);
                }
            } elseif ($role === 'sponsor') {
                $company_name = trim($_POST['company_name'] ?? '');
                $website_url = trim($_POST['website_url'] ?? '');
                $description = trim($_POST['description'] ?? '');
                
                $check = $pdo->prepare("SELECT COUNT(*) FROM sponsor_profiles WHERE user_id = ?");
                $check->execute([$user_id]);
                if ($check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO sponsor_profiles (user_id, company_name, website_url, description) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$user_id, $company_name, $website_url, $description]);
                } else {
                    $stmt = $pdo->prepare("UPDATE sponsor_profiles SET company_name = ?, website_url = ?, description = ? WHERE user_id = ?");
                    $stmt->execute([$company_name, $website_url, $description, $user_id]);
                }
            }
            $success = "Role details updated.";
        } elseif ($action === 'toggle_2fa') {
            $enable_2fa = isset($_POST['enable_2fa']) ? 1 : 0;
            $stmt = $pdo->prepare("UPDATE users SET is_2fa_enabled = ? WHERE id = ?");
            $stmt->execute([$enable_2fa, $user_id]);
            
            // Refresh user details
            $stmt_refresh = $pdo->prepare("SELECT is_2fa_enabled FROM users WHERE id = ?");
            $stmt_refresh->execute([$user_id]);
            $user['is_2fa_enabled'] = $stmt_refresh->fetchColumn();
            
            $success = $enable_2fa ? "Two-Factor Authentication enabled." : "Two-Factor Authentication disabled.";
        }
    }
}

// Fetch base user details
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Fetch specific profile based on role
$profile = [];
if ($role === 'speaker') {
    $stmt = $pdo->prepare("SELECT * FROM speaker_profiles WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $profile = $stmt->fetch() ?: [];
} elseif ($role === 'organizer') {
    $stmt = $pdo->prepare("SELECT * FROM organizer_profiles WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $profile = $stmt->fetch() ?: [];
} elseif ($role === 'sponsor') {
    $stmt = $pdo->prepare("SELECT * FROM sponsor_profiles WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $profile = $stmt->fetch() ?: [];
}

// Fetch Experiences
$stmt = $pdo->prepare("SELECT * FROM user_experiences WHERE user_id = ? ORDER BY start_date DESC");
$stmt->execute([$user_id]);
$experiences = $stmt->fetchAll();

// Fetch Educations
$stmt = $pdo->prepare("SELECT * FROM user_educations WHERE user_id = ? ORDER BY start_date DESC");
$stmt->execute([$user_id]);
$educations = $stmt->fetchAll();

$banner_img = (!empty($user['banner_picture_url']) && file_exists(__DIR__ . '/' . $user['banner_picture_url'])) ? $user['banner_picture_url'] : 'https://images.unsplash.com/photo-1579546929518-9e396f3cc809?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80';
$avatar_img = (!empty($user['profile_picture_url']) && file_exists(__DIR__ . '/' . $user['profile_picture_url'])) ? $user['profile_picture_url'] : 'https://ui-avatars.com/api/?name='.urlencode($user['username']).'&background=random&size=200';
?>

<div class="row">
    <div class="col-12">
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="bi bi-x-circle-fill me-2"></i><?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($success)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="bi bi-check-circle-fill me-2"></i><?php echo htmlspecialchars($success); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- LinkedIn Style Hero Section -->
        <div class="card border-0 shadow-sm mb-4 overflow-hidden position-relative">
            <!-- Banner Image -->
            <div style="height: 250px; background-image: url('<?php echo htmlspecialchars($banner_img); ?>'); background-size: cover; background-position: center; border-radius: 0.375rem 0.375rem 0 0;">
            </div>
            
            <div class="card-body px-4 px-md-5 pt-0 pb-4">
                <!-- Profile Header Wrapper (Avatar + Buttons) -->
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-center align-items-md-end gap-3 pb-4 border-bottom border-light" style="margin-top: -75px;">
                    <!-- Avatar -->
                    <div class="text-center text-md-start">
                        <img src="<?php echo htmlspecialchars($avatar_img); ?>" alt="Profile Avatar" class="rounded-circle border border-4 border-white shadow-sm bg-white" style="width: 150px; height: 150px; object-fit: cover;">
                    </div>
                    
                    <!-- Actions -->
                    <div class="d-flex flex-column flex-sm-row gap-2 w-100 w-md-auto justify-content-md-end mt-2 mt-md-0">
                        <button type="button" class="btn btn-outline-secondary rounded-pill px-3 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
                            <i class="bi bi-key me-1"></i> Change Password
                        </button>
                        <button type="button" class="btn btn-outline-primary rounded-pill px-3 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#editProfileModal">
                            <i class="bi bi-pencil-square me-1"></i> Edit Profile
                        </button>
                        <button type="button" class="btn btn-outline-info rounded-pill px-3 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#twoFactorModal">
                            <i class="bi bi-shield-check me-1"></i> 2FA Settings
                        </button>
                    </div>
                </div>
                
                <!-- Info Section -->
                <div class="text-center text-md-start mt-4">
                    <h2 class="fw-bold mb-1 text-dark">
                        <?php 
                        $displayName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
                        echo htmlspecialchars(!empty($displayName) ? $displayName : $user['username']); 
                        ?>
                    </h2>
                    <?php if (!empty($user['headline'])): ?>
                        <p class="fs-5 text-dark mb-1"><?php echo htmlspecialchars($user['headline']); ?></p>
                    <?php endif; ?>
                    
                    <div class="text-secondary small d-flex flex-column flex-sm-row align-items-center justify-content-center justify-content-md-start gap-2 gap-sm-3 mt-2">
                        <?php if (!empty($user['location'])): ?>
                            <span><i class="bi bi-geo-alt-fill me-1"></i> <?php echo htmlspecialchars($user['location']); ?></span>
                        <?php endif; ?>
                        <span><i class="bi bi-envelope-fill me-1"></i> <?php echo htmlspecialchars($user['email']); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- About Section -->
        <?php if (!empty($user['about_summary'])): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body p-4 p-md-5">
                <h5 class="fw-bold mb-3"><i class="bi bi-person-lines-fill me-2 text-primary"></i>About</h5>
                <p class="text-secondary mb-0 lh-lg" style="white-space: pre-wrap; font-size: 0.95rem;"><?php echo htmlspecialchars($user['about_summary']); ?></p>
            </div>
        </div>
        <?php endif; ?>

        <!-- Experience Section -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold"><i class="bi bi-briefcase-fill me-2 text-info"></i>Experience</h5>
                <button type="button" class="btn btn-sm btn-light text-primary" data-bs-toggle="modal" data-bs-target="#addExperienceModal">
                    <i class="bi bi-plus-lg fs-5"></i>
                </button>
            </div>
            <div class="card-body p-4 p-md-5">
                <?php if (empty($experiences)): ?>
                    <p class="text-muted text-center mb-0">No experiences added yet.</p>
                <?php else: ?>
                    <div class="timeline ps-3 border-start border-2 border-light">
                        <?php foreach ($experiences as $exp): 
                            $start = date('M Y', strtotime($exp['start_date']));
                            $end = $exp['is_current'] ? 'Present' : (!empty($exp['end_date']) ? date('M Y', strtotime($exp['end_date'])) : '');
                        ?>
                            <div class="position-relative mb-4 pb-2">
                                <span class="position-absolute bg-white border border-info rounded-circle" style="width: 12px; height: 12px; left: -23px; top: 5px;"></span>
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h6 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($exp['title']); ?></h6>
                                        <div class="text-dark mb-1"><?php echo htmlspecialchars($exp['company']); ?></div>
                                        <div class="text-secondary small mb-2">
                                            <?php echo $start; ?> - <?php echo $end; ?> 
                                            <?php if (!empty($exp['location'])) echo ' • ' . htmlspecialchars($exp['location']); ?>
                                        </div>
                                        <?php if (!empty($exp['description'])): ?>
                                            <p class="text-secondary mb-0 small" style="white-space: pre-wrap;"><?php echo htmlspecialchars($exp['description']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <form method="POST" action="profile" class="d-inline" onsubmit="return confirm('Delete this experience?');">
                                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                        <input type="hidden" name="action" value="delete_exp">
                                        <input type="hidden" name="id" value="<?php echo $exp['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-link text-danger"><i class="bi bi-trash"></i></button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Education Section -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0 fw-bold"><i class="bi bi-mortarboard-fill me-2 text-warning"></i>Education</h5>
                <button type="button" class="btn btn-sm btn-light text-primary" data-bs-toggle="modal" data-bs-target="#addEducationModal">
                    <i class="bi bi-plus-lg fs-5"></i>
                </button>
            </div>
            <div class="card-body p-4 p-md-5">
                <?php if (empty($educations)): ?>
                    <p class="text-muted text-center mb-0">No education added yet.</p>
                <?php else: ?>
                    <div class="timeline ps-3 border-start border-2 border-light">
                        <?php foreach ($educations as $edu): 
                            $start = !empty($edu['start_date']) ? date('Y', strtotime($edu['start_date'])) : '';
                            $end = !empty($edu['end_date']) ? date('Y', strtotime($edu['end_date'])) : '';
                        ?>
                            <div class="position-relative mb-4 pb-2">
                                <span class="position-absolute bg-white border border-warning rounded-circle" style="width: 12px; height: 12px; left: -23px; top: 5px;"></span>
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h6 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($edu['school']); ?></h6>
                                        <div class="text-dark mb-1">
                                            <?php echo htmlspecialchars($edu['degree']); ?>
                                            <?php if (!empty($edu['field_of_study'])) echo ', ' . htmlspecialchars($edu['field_of_study']); ?>
                                        </div>
                                        <?php if ($start || $end): ?>
                                            <div class="text-secondary small mb-2">
                                                <?php echo $start; ?> <?php echo ($start && $end) ? '-' : ''; ?> <?php echo $end; ?>
                                            </div>
                                        <?php endif; ?>
                                        <?php if (!empty($edu['description'])): ?>
                                            <p class="text-secondary mb-0 small" style="white-space: pre-wrap;"><?php echo htmlspecialchars($edu['description']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <form method="POST" action="profile" class="d-inline" onsubmit="return confirm('Delete this education?');">
                                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                                        <input type="hidden" name="action" value="delete_edu">
                                        <input type="hidden" name="id" value="<?php echo $edu['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-link text-danger"><i class="bi bi-trash"></i></button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Skills Section -->
        <?php if (!empty($user['skills'])): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body p-4 p-md-5">
                <h5 class="fw-bold mb-3"><i class="bi bi-star-fill me-2 text-success"></i>Skills</h5>
                <div class="d-flex flex-wrap gap-2 mt-3">
                    <?php 
                    $skills = array_filter(array_map('trim', explode(',', $user['skills'])));
                    foreach ($skills as $skill): ?>
                        <span class="badge bg-secondary bg-opacity-10 text-secondary-emphasis border px-3 py-2 fs-6 rounded-pill">
                            <?php echo htmlspecialchars($skill); ?>
                        </span>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Role Specific Details -->
        <?php if ($role !== 'user' && $role !== 'admin'): ?>
        <div class="card border-0 shadow-sm mt-5 mb-4 border-top border-4 border-secondary">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-secondary text-uppercase" style="letter-spacing: 1px;"><i class="bi bi-person-badge me-2"></i><?php echo ucfirst($role); ?> Details</h5>
            </div>
            <div class="card-body p-4">
                <form method="POST" action="profile">
                    <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                    <input type="hidden" name="action" value="update_role">
                    
                    <?php if ($role === 'speaker'): ?>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Full Name</label>
                                <input type="text" class="form-control" name="full_name" value="<?php echo htmlspecialchars($profile['full_name'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Organization</label>
                                <input type="text" class="form-control" name="organization" value="<?php echo htmlspecialchars($profile['organization'] ?? ''); ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label small fw-bold">Expertise</label>
                                <input type="text" class="form-control" name="expertise" value="<?php echo htmlspecialchars($profile['expertise'] ?? ''); ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label small fw-bold">Speaker Bio</label>
                                <textarea class="form-control" name="bio" rows="3"><?php echo htmlspecialchars($profile['bio'] ?? ''); ?></textarea>
                            </div>
                        </div>
                    <?php elseif ($role === 'organizer'): ?>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Full Name</label>
                                <input type="text" class="form-control" name="full_name" value="<?php echo htmlspecialchars($profile['full_name'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Phone</label>
                                <input type="text" class="form-control" name="phone" value="<?php echo htmlspecialchars($profile['phone'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Company</label>
                                <input type="text" class="form-control" name="company" value="<?php echo htmlspecialchars($profile['company'] ?? ''); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Department</label>
                                <input type="text" class="form-control" name="department" value="<?php echo htmlspecialchars($profile['department'] ?? ''); ?>">
                            </div>
                        </div>
                    <?php elseif ($role === 'sponsor'): ?>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Company Name</label>
                                <input type="text" class="form-control" name="company_name" value="<?php echo htmlspecialchars($profile['company_name'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label small fw-bold">Website URL</label>
                                <input type="url" class="form-control" name="website_url" value="<?php echo htmlspecialchars($profile['website_url'] ?? ''); ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label small fw-bold">Company Description</label>
                                <textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars($profile['description'] ?? ''); ?></textarea>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <div class="mt-4 text-end">
                        <button type="submit" class="btn btn-secondary px-4">Update <?php echo ucfirst($role); ?> Details</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

    </div>
</div>

<!-- Edit Profile Modal -->
<div class="modal fade" id="editProfileModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold">Edit Profile</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="profile" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                <input type="hidden" name="action" value="update_profile">
                <input type="hidden" name="existing_profile_picture" value="<?php echo htmlspecialchars($user['profile_picture_url'] ?? ''); ?>">
                <input type="hidden" name="existing_banner_picture" value="<?php echo htmlspecialchars($user['banner_picture_url'] ?? ''); ?>">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <label class="form-label small fw-bold">First Name</label>
                            <input type="text" class="form-control" name="first_name" value="<?php echo htmlspecialchars($user['first_name'] ?? ''); ?>" required>
                        </div>
                        <div class="col-12 col-md-6">
                            <label class="form-label small fw-bold">Last Name</label>
                            <input type="text" class="form-control" name="last_name" value="<?php echo htmlspecialchars($user['last_name'] ?? ''); ?>" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Email Address</label>
                            <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Headline</label>
                            <input type="text" class="form-control" name="headline" value="<?php echo htmlspecialchars($user['headline'] ?? ''); ?>" placeholder="e.g. Software Engineer at Google">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Location</label>
                            <input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($user['location'] ?? ''); ?>" placeholder="e.g. San Francisco Bay Area">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">About (Summary)</label>
                            <textarea class="form-control" name="about_summary" rows="4"><?php echo htmlspecialchars($user['about_summary'] ?? ''); ?></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Skills (comma separated)</label>
                            <input type="text" class="form-control" name="skills" value="<?php echo htmlspecialchars($user['skills'] ?? ''); ?>" placeholder="e.g. PHP, JavaScript, Project Management">
                        </div>
                        
                        <hr class="my-4">
                        <h6 class="fw-bold mb-3">Images</h6>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Profile Picture</label>
                            <div class="drop-zone border rounded p-3 text-center position-relative" id="drop-zone-profile" style="border: 2px dashed #dee2e6 !important; cursor: pointer; transition: all 0.2s; background: #f8f9fa;">
                                <i class="bi bi-cloud-arrow-up fs-3 text-secondary" id="icon-profile"></i>
                                <p class="small text-secondary mb-1 mt-2" id="text-profile">Drag & drop image here<br>or click to browse</p>
                                <input type="file" class="form-control" name="profile_picture" id="profile_picture" accept="image/*" style="opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer;">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Background Banner</label>
                            <div class="drop-zone border rounded p-3 text-center position-relative" id="drop-zone-banner" style="border: 2px dashed #dee2e6 !important; cursor: pointer; transition: all 0.2s; background: #f8f9fa;">
                                <i class="bi bi-image fs-3 text-secondary" id="icon-banner"></i>
                                <p class="small text-secondary mb-1 mt-2" id="text-banner">Drag & drop image here<br>or click to browse</p>
                                <input type="file" class="form-control" name="banner_picture" id="banner_picture" accept="image/*" style="opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer;">
                            </div>
                        </div>
                        
                        <script>
                            function setupDropZone(inputId, zoneId, textId, iconId) {
                                const dropZone = document.getElementById(zoneId);
                                const input = document.getElementById(inputId);
                                const text = document.getElementById(textId);
                                const icon = document.getElementById(iconId);

                                ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                                    dropZone.addEventListener(eventName, preventDefaults, false);
                                });

                                function preventDefaults(e) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                }

                                ['dragenter', 'dragover'].forEach(eventName => {
                                    dropZone.addEventListener(eventName, highlight, false);
                                });

                                ['dragleave', 'drop'].forEach(eventName => {
                                    dropZone.addEventListener(eventName, unhighlight, false);
                                });

                                function highlight(e) {
                                    dropZone.style.backgroundColor = '#e9ecef';
                                    dropZone.style.borderColor = '#0d6efd';
                                }

                                function unhighlight(e) {
                                    dropZone.style.backgroundColor = '#f8f9fa';
                                    dropZone.style.borderColor = '#dee2e6';
                                }

                                dropZone.addEventListener('drop', handleDrop, false);

                                function handleDrop(e) {
                                    let dt = e.dataTransfer;
                                    let files = dt.files;
                                    input.files = files;
                                    updateUI();
                                }
                                
                                input.addEventListener('change', updateUI);
                                
                                function updateUI() {
                                    if(input.files && input.files[0]) {
                                        icon.className = 'bi bi-check-circle-fill fs-3 text-success';
                                        text.innerHTML = `<span class='text-success fw-bold'>${input.files[0].name}</span>`;
                                        dropZone.style.borderColor = '#198754';
                                    }
                                }
                            }
                            
                            document.addEventListener('DOMContentLoaded', () => {
                                setupDropZone('profile_picture', 'drop-zone-profile', 'text-profile', 'icon-profile');
                                setupDropZone('banner_picture', 'drop-zone-banner', 'text-banner', 'icon-banner');
                            });
                        </script>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4 fw-bold">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Experience Modal -->
<div class="modal fade" id="addExperienceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold">Add Experience</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="profile">
                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                <input type="hidden" name="action" value="add_experience">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label small fw-bold">Title *</label>
                            <input type="text" class="form-control" name="title" required placeholder="Ex: Product Manager">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Company *</label>
                            <input type="text" class="form-control" name="company" required placeholder="Ex: Microsoft">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Location</label>
                            <input type="text" class="form-control" name="location" placeholder="Ex: London, United Kingdom">
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">Start Date *</label>
                            <input type="date" class="form-control" name="start_date" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">End Date</label>
                            <input type="date" class="form-control" name="end_date">
                        </div>
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_current" id="is_current" value="1">
                                <label class="form-check-label small" for="is_current">I am currently working in this role</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Description</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4 fw-bold">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Education Modal -->
<div class="modal fade" id="addEducationModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold">Add Education</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="profile">
                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                <input type="hidden" name="action" value="add_education">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label small fw-bold">School *</label>
                            <input type="text" class="form-control" name="school" required placeholder="Ex: Boston University">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Degree</label>
                            <input type="text" class="form-control" name="degree" placeholder="Ex: Bachelor's">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Field of study</label>
                            <input type="text" class="form-control" name="field_of_study" placeholder="Ex: Business">
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">Start Date (Approx)</label>
                            <input type="date" class="form-control" name="start_date">
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">End Date (or expected)</label>
                            <input type="date" class="form-control" name="end_date">
                        </div>
                        <div class="col-12">
                            <label class="form-label small fw-bold">Description / Activities</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4 fw-bold">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Change Password Modal -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold"><i class="bi bi-key-fill me-2 text-warning"></i>Change Password</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="profile">
                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                <input type="hidden" name="action" value="change_password">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label for="current_password" class="form-label small fw-bold">Current Password *</label>
                        <input type="password" class="form-control" name="current_password" required>
                    </div>
                    <div class="mb-3">
                        <label for="new_password" class="form-label small fw-bold">New Password * (Min 6 characters)</label>
                        <input type="password" class="form-control" name="new_password" required minlength="6">
                    </div>
                    <div class="mb-3">
                        <label for="confirm_password" class="form-label small fw-bold">Confirm New Password *</label>
                        <input type="password" class="form-control" name="confirm_password" required minlength="6">
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning px-4 fw-bold">Update Password</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Two-Factor Authentication Modal -->
<div class="modal fade" id="twoFactorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-light">
                <h5 class="modal-title fw-bold"><i class="bi bi-shield-lock-fill me-2 text-info"></i>Two-Factor Authentication</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="profile">
                <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                <input type="hidden" name="action" value="toggle_2fa">
                <div class="modal-body p-4 text-center">
                    <p class="text-secondary small mb-4">
                        Protect your account with Two-Factor Authentication. When enabled, you will be required to enter a secure code sent to your email each time you log in.
                    </p>
                    <div class="form-check form-switch d-inline-block fs-5 text-start">
                        <input class="form-check-input shadow-none" type="checkbox" role="switch" id="enable_2fa" name="enable_2fa" value="1" <?php echo (!empty($user['is_2fa_enabled'])) ? 'checked' : ''; ?>>
                        <label class="form-check-label fw-bold ms-2 text-dark" for="enable_2fa">Enable 2FA (Email & WhatsApp)</label>
                    </div>
                </div>
                <div class="modal-footer bg-light border-top-0">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-info px-4 fw-bold text-white">Save Preferences</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
