<?php
require_once '../config/config.php';
requireLogin('candidate');

$database = new Database();
$db = $database->getConnection();

$candidate_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Get candidate info
$stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
$stmt->execute([$candidate_id]);
$candidate = $stmt->fetch();

// Get or create resume
$resume_id = isset($_GET['resume_id']) ? (int)$_GET['resume_id'] : null;
$resume = null;

if ($resume_id) {
    $stmt = $db->prepare("SELECT * FROM resumes WHERE id = ? AND candidate_id = ?");
    $stmt->execute([$resume_id, $candidate_id]);
    $resume = $stmt->fetch();
}

// Get all CV data
$stmt = $db->prepare("SELECT * FROM education WHERE candidate_id = ? ORDER BY start_date DESC");
$stmt->execute([$candidate_id]);
$education_records = $stmt->fetchAll();

$stmt = $db->prepare("SELECT * FROM work_experience WHERE candidate_id = ? ORDER BY start_date DESC");
$stmt->execute([$candidate_id]);
$experience_records = $stmt->fetchAll();

$stmt = $db->prepare("SELECT * FROM work_references WHERE candidate_id = ? ORDER BY created_at DESC");
$stmt->execute([$candidate_id]);
$references = $stmt->fetchAll();

$stmt = $db->prepare("SELECT * FROM certificates WHERE candidate_id = ? ORDER BY issue_date DESC");
$stmt->execute([$candidate_id]);
$certificates = $stmt->fetchAll();

$stmt = $db->prepare("SELECT * FROM candidate_documents WHERE candidate_id = ? ORDER BY created_at DESC");
$stmt->execute([$candidate_id]);
$documents = $stmt->fetchAll();

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    
    if ($action === 'save_resume') {
        $title = sanitize($_POST['title']);
        $summary = sanitize($_POST['summary']);
        $skills = sanitize($_POST['skills']);
        $is_primary = isset($_POST['is_primary']) ? 1 : 0;
        
        if (empty($title)) {
            $error = 'Resume title is required.';
        } else {
            try {
                if ($resume_id && $resume) {
                    $stmt = $db->prepare("UPDATE resumes SET title = ?, summary = ?, skills = ?, is_primary = ? WHERE id = ? AND candidate_id = ?");
                    $stmt->execute([$title, $summary, $skills, $is_primary, $resume_id, $candidate_id]);
                } else {
                    $stmt = $db->prepare("INSERT INTO resumes (candidate_id, title, summary, skills, is_primary) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$candidate_id, $title, $summary, $skills, $is_primary]);
                    $resume_id = $db->lastInsertId();
                }
                
                if ($is_primary) {
                    $stmt = $db->prepare("UPDATE resumes SET is_primary = 0 WHERE candidate_id = ? AND id != ?");
                    $stmt->execute([$candidate_id, $resume_id]);
                }
                
                $success = 'Resume saved successfully!';
                
                $stmt = $db->prepare("SELECT * FROM resumes WHERE id = ? AND candidate_id = ?");
                $stmt->execute([$resume_id, $candidate_id]);
                $resume = $stmt->fetch();
                
            } catch (PDOException $e) {
                $error = 'Error saving resume. Please try again.';
            }
        }
    }
    
    elseif ($action === 'add_education') {
        $institution = sanitize($_POST['institution']);
        $degree = sanitize($_POST['degree']);
        $field_of_study = sanitize($_POST['field_of_study']);
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $grade = sanitize($_POST['grade']);
        $description = sanitize($_POST['description']);
        
        if (empty($institution) || empty($degree)) {
            $error = 'Institution and degree are required.';
        } else {
            try {
                $stmt = $db->prepare("INSERT INTO education (candidate_id, institution, degree, field_of_study, start_date, end_date, grade, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$candidate_id, $institution, $degree, $field_of_study, $start_date ?: null, $end_date ?: null, $grade, $description]);
                $success = 'Education record added successfully!';
                
                $stmt = $db->prepare("SELECT * FROM education WHERE candidate_id = ? ORDER BY start_date DESC");
                $stmt->execute([$candidate_id]);
                $education_records = $stmt->fetchAll();
                
            } catch (PDOException $e) {
                $error = 'Error adding education record. Please try again.';
            }
        }
    }
    
    elseif ($action === 'edit_education') {
        $edu_id = (int)$_POST['edu_id'];
        $institution = sanitize($_POST['institution']);
        $degree = sanitize($_POST['degree']);
        $field_of_study = sanitize($_POST['field_of_study']);
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $grade = sanitize($_POST['grade']);
        $description = sanitize($_POST['description']);
        
        if (empty($institution) || empty($degree)) {
            $error = 'Institution and degree are required.';
        } else {
            try {
                $stmt = $db->prepare("UPDATE education SET institution = ?, degree = ?, field_of_study = ?, start_date = ?, end_date = ?, grade = ?, description = ? WHERE id = ? AND candidate_id = ?");
                $stmt->execute([$institution, $degree, $field_of_study, $start_date ?: null, $end_date ?: null, $grade, $description, $edu_id, $candidate_id]);
                $success = 'Education record updated successfully!';
                
                $stmt = $db->prepare("SELECT * FROM education WHERE candidate_id = ? ORDER BY start_date DESC");
                $stmt->execute([$candidate_id]);
                $education_records = $stmt->fetchAll();
                
            } catch (PDOException $e) {
                $error = 'Error updating education record. Please try again.';
            }
        }
    }
    
    elseif ($action === 'delete_education') {
        $edu_id = (int)$_POST['edu_id'];
        
        try {
            $stmt = $db->prepare("DELETE FROM education WHERE id = ? AND candidate_id = ?");
            $stmt->execute([$edu_id, $candidate_id]);
            $success = 'Education record deleted successfully!';
            
            $stmt = $db->prepare("SELECT * FROM education WHERE candidate_id = ? ORDER BY start_date DESC");
            $stmt->execute([$candidate_id]);
            $education_records = $stmt->fetchAll();
            
        } catch (PDOException $e) {
            $error = 'Error deleting education record. Please try again.';
        }
    }
    
    elseif ($action === 'add_experience') {
        $company_name = sanitize($_POST['company_name']);
        $position = sanitize($_POST['position']);
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $is_current = isset($_POST['is_current']) ? 1 : 0;
        $description = sanitize($_POST['description']);
        
        if (empty($company_name) || empty($position)) {
            $error = 'Company name and position are required.';
        } else {
            try {
                $stmt = $db->prepare("INSERT INTO work_experience (candidate_id, company_name, position, start_date, end_date, is_current, description) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$candidate_id, $company_name, $position, $start_date ?: null, $end_date ?: null, $is_current, $description]);
                $success = 'Work experience added successfully!';
                
                $stmt = $db->prepare("SELECT * FROM work_experience WHERE candidate_id = ? ORDER BY start_date DESC");
                $stmt->execute([$candidate_id]);
                $experience_records = $stmt->fetchAll();
                
            } catch (PDOException $e) {
                $error = 'Error adding work experience. Please try again.';
            }
        }
    }
    
    elseif ($action === 'edit_experience') {
        $exp_id = (int)$_POST['exp_id'];
        $company_name = sanitize($_POST['company_name']);
        $position = sanitize($_POST['position']);
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $is_current = isset($_POST['is_current']) ? 1 : 0;
        $description = sanitize($_POST['description']);
        
        if (empty($company_name) || empty($position)) {
            $error = 'Company name and position are required.';
        } else {
            try {
                $stmt = $db->prepare("UPDATE work_experience SET company_name = ?, position = ?, start_date = ?, end_date = ?, is_current = ?, description = ? WHERE id = ? AND candidate_id = ?");
                $stmt->execute([$company_name, $position, $start_date ?: null, $end_date ?: null, $is_current, $description, $exp_id, $candidate_id]);
                $success = 'Work experience updated successfully!';
                
                $stmt = $db->prepare("SELECT * FROM work_experience WHERE candidate_id = ? ORDER BY start_date DESC");
                $stmt->execute([$candidate_id]);
                $experience_records = $stmt->fetchAll();
                
            } catch (PDOException $e) {
                $error = 'Error updating work experience. Please try again.';
            }
        }
    }
    
    elseif ($action === 'delete_experience') {
        $exp_id = (int)$_POST['exp_id'];
        
        try {
            $stmt = $db->prepare("DELETE FROM work_experience WHERE id = ? AND candidate_id = ?");
            $stmt->execute([$exp_id, $candidate_id]);
            $success = 'Work experience deleted successfully!';
            
            $stmt = $db->prepare("SELECT * FROM work_experience WHERE candidate_id = ? ORDER BY start_date DESC");
            $stmt->execute([$candidate_id]);
            $experience_records = $stmt->fetchAll();
            
        } catch (PDOException $e) {
            $error = 'Error deleting work experience. Please try again.';
        }
    }
    
    elseif ($action === 'add_reference') {
        $name = sanitize($_POST['ref_name']);
        $position = sanitize($_POST['ref_position']);
        $company = sanitize($_POST['ref_company']);
        $email = sanitize($_POST['ref_email']);
        $phone = sanitize($_POST['ref_phone']);
        $relationship = sanitize($_POST['ref_relationship']);
        $years_known = (int)$_POST['years_known'];
        
        if (empty($name) || empty($email)) {
            $error = 'Reference name and email are required.';
        } else {
            try {
                $stmt = $db->prepare("INSERT INTO work_references (candidate_id, name, position, company, email, phone, relationship, years_known) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$candidate_id, $name, $position, $company, $email, $phone, $relationship, $years_known]);
                $success = 'Work reference added successfully!';
                
                $stmt = $db->prepare("SELECT * FROM work_references WHERE candidate_id = ? ORDER BY created_at DESC");
                $stmt->execute([$candidate_id]);
                $references = $stmt->fetchAll();
                
            } catch (PDOException $e) {
                $error = 'Error adding work reference. Please try again.';
            }
        }
    }
    
    elseif ($action === 'add_certificate') {
        $title = sanitize($_POST['cert_title']);
        $issuing_organization = sanitize($_POST['cert_organization']);
        $issue_date = $_POST['cert_issue_date'];
        $expiry_date = $_POST['cert_expiry_date'];
        $credential_id = sanitize($_POST['credential_id']);
        $credential_url = sanitize($_POST['credential_url']);
        $description = sanitize($_POST['cert_description']);
        
        if (empty($title) || empty($issuing_organization)) {
            $error = 'Certificate title and issuing organization are required.';
        } else {
            try {
                // Handle certificate file upload
                $file_path = null;
                if (isset($_FILES['cert_file']) && $_FILES['cert_file']['error'] === UPLOAD_ERR_OK) {
                    $upload_dir = '../uploads/certificates/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $allowed_types = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif'];
                    $file_type = $_FILES['cert_file']['type'];
                    
                    if (in_array($file_type, $allowed_types)) {
                        $file_extension = pathinfo($_FILES['cert_file']['name'], PATHINFO_EXTENSION);
                        $filename = uniqid() . '.' . $file_extension;
                        $upload_path = $upload_dir . $filename;
                        
                        if (move_uploaded_file($_FILES['cert_file']['tmp_name'], $upload_path)) {
                            $file_path = $filename;
                        }
                    }
                }
                
                $stmt = $db->prepare("INSERT INTO certificates (candidate_id, title, issuing_organization, issue_date, expiry_date, credential_id, credential_url, description, file_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$candidate_id, $title, $issuing_organization, $issue_date ?: null, $expiry_date ?: null, $credential_id, $credential_url, $description, $file_path]);
                $success = 'Certificate added successfully!';
                
                $stmt = $db->prepare("SELECT * FROM certificates WHERE candidate_id = ? ORDER BY issue_date DESC");
                $stmt->execute([$candidate_id]);
                $certificates = $stmt->fetchAll();
                
            } catch (PDOException $e) {
                $error = 'Error adding certificate. Please try again.';
            }
        }
    }
    
    elseif ($action === 'upload_document') {
        $document_type = $_POST['document_type'];
        $title = sanitize($_POST['doc_title']);
        $description = sanitize($_POST['doc_description']);
        $is_public = isset($_POST['is_public']) ? 1 : 0;
        
        if (empty($title) || !isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
            $error = 'Document title and file are required.';
        } else {
            try {
                $upload_dir = '../uploads/documents/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $allowed_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png'];
                $file_type = $_FILES['document']['type'];
                $file_size = $_FILES['document']['size'];
                
                if (!in_array($file_type, $allowed_types)) {
                    $error = 'Only PDF, Word documents, and images are allowed.';
                } elseif ($file_size > 5 * 1024 * 1024) { // 5MB limit
                    $error = 'File size must be less than 5MB.';
                } else {
                    $file_extension = pathinfo($_FILES['document']['name'], PATHINFO_EXTENSION);
                    $filename = uniqid() . '.' . $file_extension;
                    $upload_path = $upload_dir . $filename;
                    
                    if (move_uploaded_file($_FILES['document']['tmp_name'], $upload_path)) {
                        $stmt = $db->prepare("INSERT INTO candidate_documents (candidate_id, document_type, title, file_path, file_size, file_type, description, is_public) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([$candidate_id, $document_type, $title, $filename, $file_size, $file_type, $description, $is_public]);
                        $success = 'Document uploaded successfully!';
                        
                        $stmt = $db->prepare("SELECT * FROM candidate_documents WHERE candidate_id = ? ORDER BY created_at DESC");
                        $stmt->execute([$candidate_id]);
                        $documents = $stmt->fetchAll();
                    } else {
                        $error = 'Failed to upload document.';
                    }
                }
                
            } catch (PDOException $e) {
                $error = 'Error uploading document. Please try again.';
            }
        }
    }
}

// Get all resumes for candidate
$stmt = $db->prepare("SELECT * FROM resumes WHERE candidate_id = ? ORDER BY is_primary DESC, created_at DESC");
$stmt->execute([$candidate_id]);
$all_resumes = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enhanced CV Builder - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .cv-section { border: 1px solid #dee2e6; border-radius: 8px; padding: 1.5rem; margin-bottom: 1.5rem; background-color: white; }
        .cv-section h4 { color: var(--primary-color); border-bottom: 2px solid var(--primary-color); padding-bottom: 0.5rem; margin-bottom: 1rem; }
        .item-card { border-left: 3px solid #e9ecef; padding-left: 1rem; margin-bottom: 1rem; background: #f8f9fa; padding: 1rem; border-radius: 0 8px 8px 0; }
        .file-upload-area { border: 2px dashed #ccc; border-radius: 8px; padding: 2rem; text-align: center; transition: border-color 0.3s ease; }
        .file-upload-area:hover { border-color: var(--primary-color); }
        
        /* Personal Information Styles */
        .profile-photo { width: 120px; height: 120px; border-radius: 50%; object-fit: cover; border: 4px solid #e9ecef; }
        .profile-placeholder { width: 120px; height: 120px; border-radius: 50%; background: #f8f9fa; border: 4px solid #e9ecef; display: inline-flex; align-items: center; justify-content: center; }
        .candidate-name { color: #2c3e50; font-weight: 600; }
        .contact-info a { color: #495057; text-decoration: none; }
        .contact-info a:hover { color: var(--primary-color); }
        .professional-summary p { font-size: 0.95rem; line-height: 1.6; }
        .key-skills .badge { font-size: 0.8rem; }
        
        /* Print Styles */
        @media print {
            .sidebar, .navbar, .btn, .dropdown, .alert, form, .no-print { display: none !important; }
            .container-fluid { margin: 0; padding: 0; }
            .col-md-9, .col-lg-10 { width: 100% !important; flex: none !important; }
            .cv-section { border: 1px solid #ddd; margin-bottom: 1rem; page-break-inside: avoid; }
            body { font-size: 12pt; line-height: 1.4; }
            h1, h2, h3, h4, h5, h6 { page-break-after: avoid; }
            .profile-photo { width: 100px; height: 100px; }
            .candidate-name { font-size: 24pt; color: #000; }
            .contact-info { font-size: 11pt; }
            .item-card { border-left: 2px solid #000; margin-bottom: 0.5rem; }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['first_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-user me-2"></i>My Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="cv-builder.php">
                                <i class="fas fa-file-alt me-2"></i>CV Builder
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-paper-plane me-2"></i>My Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../jobs.php">
                                <i class="fas fa-search me-2"></i>Browse Jobs
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
                        <h1 class="h2">
                            <i class="fas fa-file-alt me-2"></i>Enhanced CV Builder
                        </h1>
                        <div>
                            <button class="btn btn-success me-2" onclick="window.print()">
                                <i class="fas fa-print me-1"></i>Print CV
                            </button>
                            <a href="dashboard.php" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-1"></i>Back to Dashboard
                            </a>
                        </div>
                    </div>

                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                        </div>
                    <?php endif; ?>

                    <!-- Resume Header -->
                    <div class="cv-section no-print">
                        <h4><i class="fas fa-file-alt me-2"></i>Resume Information</h4>
                        <form method="POST">
                            <input type="hidden" name="action" value="save_resume">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="title" class="form-label">Resume Title *</label>
                                    <input type="text" class="form-control" id="title" name="title" 
                                           value="<?php echo $resume ? htmlspecialchars($resume['title']) : ''; ?>" 
                                           placeholder="e.g., Software Developer Resume" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <div class="form-check mt-4">
                                        <input class="form-check-input" type="checkbox" id="is_primary" name="is_primary" 
                                               <?php echo ($resume && $resume['is_primary']) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="is_primary">
                                            Set as Primary Resume
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="summary" class="form-label">Professional Summary</label>
                                <textarea class="form-control" id="summary" name="summary" rows="4" 
                                          placeholder="Brief professional summary highlighting your key strengths and career objectives..."><?php echo $resume ? htmlspecialchars($resume['summary']) : ''; ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="skills" class="form-label">Key Skills</label>
                                <textarea class="form-control" id="skills" name="skills" rows="3" 
                                          placeholder="List your key skills separated by commas (e.g., PHP, JavaScript, Project Management, etc.)"><?php echo $resume ? htmlspecialchars($resume['skills']) : ''; ?></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i>Save Resume Info
                            </button>
                        </form>
                    </div>

                    <!-- Personal Information Section -->
                    <div class="cv-section" id="personal-info-section">
                        <div class="card">
                            <div class="card-body text-center">
                                <?php if ($candidate['profile_picture']): ?>
                                    <img src="../uploads/profiles/<?php echo $candidate['profile_picture']; ?>" 
                                         alt="Profile Picture" 
                                         class="profile-photo mb-3">
                                <?php else: ?>
                                    <div class="profile-placeholder mb-3">
                                        <i class="fas fa-user fa-3x text-muted"></i>
                                    </div>
                                <?php endif; ?>
                                
                                <h2 class="candidate-name mb-2">
                                    <?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?>
                                </h2>
                                
                                <?php if ($resume && $resume['title']): ?>
                                    <h5 class="text-muted mb-3"><?php echo htmlspecialchars($resume['title']); ?></h5>
                                <?php endif; ?>
                                
                                <div class="contact-info">
                                    <div class="row justify-content-center">
                                        <div class="col-md-6">
                                            <?php if ($candidate['email']): ?>
                                                <p class="mb-2">
                                                    <i class="fas fa-envelope me-2 text-primary"></i>
                                                    <a href="mailto:<?php echo $candidate['email']; ?>"><?php echo htmlspecialchars($candidate['email']); ?></a>
                                                </p>
                                            <?php endif; ?>
                                            
                                            <?php if ($candidate['phone']): ?>
                                                <p class="mb-2">
                                                    <i class="fas fa-phone me-2 text-primary"></i>
                                                    <a href="tel:<?php echo $candidate['phone']; ?>"><?php echo htmlspecialchars($candidate['phone']); ?></a>
                                                </p>
                                            <?php endif; ?>
                                            
                                            <?php if ($candidate['address']): ?>
                                                <p class="mb-2">
                                                    <i class="fas fa-map-marker-alt me-2 text-primary"></i>
                                                    <?php echo htmlspecialchars($candidate['address']); ?>
                                                </p>
                                            <?php endif; ?>
                                            
                                            <?php if ($candidate['date_of_birth']): ?>
                                                <p class="mb-2">
                                                    <i class="fas fa-birthday-cake me-2 text-primary"></i>
                                                    <?php echo date('F j, Y', strtotime($candidate['date_of_birth'])); ?>
                                                </p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <?php if ($resume && $resume['summary']): ?>
                                    <div class="professional-summary mt-4">
                                        <h5 class="mb-2">Professional Summary</h5>
                                        <p class="text-muted"><?php echo nl2br(htmlspecialchars($resume['summary'])); ?></p>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($resume && $resume['skills']): ?>
                                    <div class="key-skills mt-4">
                                        <h5 class="mb-2">Key Skills</h5>
                                        <?php 
                                        $skills = explode(',', $resume['skills']);
                                        foreach ($skills as $skill): 
                                            $skill = trim($skill);
                                            if ($skill):
                                        ?>
                                            <span class="badge bg-primary me-1 mb-1"><?php echo htmlspecialchars($skill); ?></span>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-6">
                            <!-- Education Section -->
                            <div class="cv-section">
                                <h4><i class="fas fa-graduation-cap me-2"></i>Education</h4>
                                
                                <?php foreach ($education_records as $edu): ?>
                                    <div class="item-card">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <h6><?php echo htmlspecialchars($edu['degree']); ?></h6>
                                                <p class="mb-1"><strong><?php echo htmlspecialchars($edu['institution']); ?></strong></p>
                                                <?php if ($edu['field_of_study']): ?>
                                                    <p class="mb-1">Field: <?php echo htmlspecialchars($edu['field_of_study']); ?></p>
                                                <?php endif; ?>
                                                <?php if ($edu['start_date'] || $edu['end_date']): ?>
                                                    <p class="mb-1">
                                                        <small class="text-muted">
                                                            <?php echo $edu['start_date'] ? date('M Y', strtotime($edu['start_date'])) : ''; ?>
                                                            <?php echo ($edu['start_date'] && $edu['end_date']) ? ' - ' : ''; ?>
                                                            <?php echo $edu['end_date'] ? date('M Y', strtotime($edu['end_date'])) : ''; ?>
                                                        </small>
                                                    </p>
                                                <?php endif; ?>
                                                <?php if ($edu['grade']): ?>
                                                    <p class="mb-1"><small>Grade: <?php echo htmlspecialchars($edu['grade']); ?></small></p>
                                                <?php endif; ?>
                                                <?php if ($edu['description']): ?>
                                                    <p class="mb-0"><small><?php echo nl2br(htmlspecialchars($edu['description'])); ?></small></p>
                                                <?php endif; ?>
                                            </div>
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                    <i class="fas fa-ellipsis-v"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="#" onclick="editEducation(<?php echo $edu['id']; ?>)">
                                                        <i class="fas fa-edit me-2"></i>Edit
                                                    </a></li>
                                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteEducation(<?php echo $edu['id']; ?>)">
                                                        <i class="fas fa-trash me-2"></i>Delete
                                                    </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>

                                <form method="POST" class="mt-3 no-print">
                                    <input type="hidden" name="action" value="add_education">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="institution" placeholder="Institution *" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="degree" placeholder="Degree/Qualification *" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="field_of_study" placeholder="Field of Study">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="grade" placeholder="Grade/GPA">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Start Date</label>
                                            <input type="date" class="form-control" name="start_date">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">End Date</label>
                                            <input type="date" class="form-control" name="end_date">
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <textarea class="form-control" name="description" rows="2" placeholder="Additional details (optional)"></textarea>
                                    </div>
                                    <button type="submit" class="btn btn-success btn-sm">
                                        <i class="fas fa-plus me-1"></i>Add Education
                                    </button>
                                </form>
                            </div>

                            <!-- Work Experience Section -->
                            <div class="cv-section">
                                <h4><i class="fas fa-briefcase me-2"></i>Work Experience</h4>
                                
                                <?php foreach ($experience_records as $exp): ?>
                                    <div class="item-card">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <h6><?php echo htmlspecialchars($exp['position']); ?></h6>
                                                <p class="mb-1"><strong><?php echo htmlspecialchars($exp['company_name']); ?></strong></p>
                                                <p class="mb-1">
                                                    <small class="text-muted">
                                                        <?php echo $exp['start_date'] ? date('M Y', strtotime($exp['start_date'])) : ''; ?>
                                                        <?php echo $exp['start_date'] ? ' - ' : ''; ?>
                                                        <?php echo $exp['is_current'] ? 'Present' : ($exp['end_date'] ? date('M Y', strtotime($exp['end_date'])) : ''); ?>
                                                    </small>
                                                </p>
                                                <?php if ($exp['description']): ?>
                                                    <p class="mb-0"><small><?php echo nl2br(htmlspecialchars($exp['description'])); ?></small></p>
                                                <?php endif; ?>
                                            </div>
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                    <i class="fas fa-ellipsis-v"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="#" onclick="editExperience(<?php echo $exp['id']; ?>)">
                                                        <i class="fas fa-edit me-2"></i>Edit
                                                    </a></li>
                                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteExperience(<?php echo $exp['id']; ?>)">
                                                        <i class="fas fa-trash me-2"></i>Delete
                                                    </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>

                                <form method="POST" class="mt-3 no-print">
                                    <input type="hidden" name="action" value="add_experience">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="company_name" placeholder="Company Name *" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="position" placeholder="Position/Title *" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-5 mb-3">
                                            <label class="form-label">Start Date</label>
                                            <input type="date" class="form-control" name="start_date">
                                        </div>
                                        <div class="col-md-5 mb-3">
                                            <label class="form-label">End Date</label>
                                            <input type="date" class="form-control" name="end_date">
                                        </div>
                                        <div class="col-md-2 mb-3">
                                            <div class="form-check mt-4">
                                                <input class="form-check-input" type="checkbox" name="is_current">
                                                <label class="form-check-label">Current</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <textarea class="form-control" name="description" rows="3" placeholder="Job responsibilities and achievements"></textarea>
                                    </div>
                                    <button type="submit" class="btn btn-success btn-sm">
                                        <i class="fas fa-plus me-1"></i>Add Experience
                                    </button>
                                </form>
                            </div>
                        </div>

                        <div class="col-lg-6">
                            <!-- Work References Section -->
                            <div class="cv-section">
                                <h4><i class="fas fa-users me-2"></i>Work References</h4>
                                
                                <?php foreach ($references as $ref): ?>
                                    <div class="item-card">
                                        <h6><?php echo htmlspecialchars($ref['name']); ?></h6>
                                        <?php if ($ref['position']): ?>
                                            <p class="mb-1"><?php echo htmlspecialchars($ref['position']); ?></p>
                                        <?php endif; ?>
                                        <?php if ($ref['company']): ?>
                                            <p class="mb-1"><strong><?php echo htmlspecialchars($ref['company']); ?></strong></p>
                                        <?php endif; ?>
                                        <p class="mb-1"><small><i class="fas fa-envelope me-1"></i><?php echo htmlspecialchars($ref['email']); ?></small></p>
                                        <?php if ($ref['phone']): ?>
                                            <p class="mb-1"><small><i class="fas fa-phone me-1"></i><?php echo htmlspecialchars($ref['phone']); ?></small></p>
                                        <?php endif; ?>
                                        <?php if ($ref['relationship']): ?>
                                            <p class="mb-1"><small>Relationship: <?php echo htmlspecialchars($ref['relationship']); ?></small></p>
                                        <?php endif; ?>
                                        <?php if ($ref['years_known']): ?>
                                            <p class="mb-0"><small>Known for: <?php echo $ref['years_known']; ?> years</small></p>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>

                                <form method="POST" class="mt-3 no-print">
                                    <input type="hidden" name="action" value="add_reference">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="ref_name" placeholder="Full Name *" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="email" class="form-control" name="ref_email" placeholder="Email Address *" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="ref_position" placeholder="Position/Title">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="ref_company" placeholder="Company">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="tel" class="form-control" name="ref_phone" placeholder="Phone Number">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="ref_relationship" placeholder="Relationship (e.g., Manager)">
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <input type="number" class="form-control" name="years_known" placeholder="Years known" min="0" max="50">
                                    </div>
                                    <button type="submit" class="btn btn-success btn-sm">
                                        <i class="fas fa-plus me-1"></i>Add Reference
                                    </button>
                                </form>
                            </div>

                            <!-- Certificates Section -->
                            <div class="cv-section">
                                <h4><i class="fas fa-certificate me-2"></i>Certificates & Qualifications</h4>
                                
                                <?php foreach ($certificates as $cert): ?>
                                    <div class="item-card">
                                        <h6><?php echo htmlspecialchars($cert['title']); ?></h6>
                                        <p class="mb-1"><strong><?php echo htmlspecialchars($cert['issuing_organization']); ?></strong></p>
                                        <?php if ($cert['issue_date']): ?>
                                            <p class="mb-1"><small>Issued: <?php echo date('M Y', strtotime($cert['issue_date'])); ?></small></p>
                                        <?php endif; ?>
                                        <?php if ($cert['expiry_date']): ?>
                                            <p class="mb-1"><small>Expires: <?php echo date('M Y', strtotime($cert['expiry_date'])); ?></small></p>
                                        <?php endif; ?>
                                        <?php if ($cert['credential_id']): ?>
                                            <p class="mb-1"><small>Credential ID: <?php echo htmlspecialchars($cert['credential_id']); ?></small></p>
                                        <?php endif; ?>
                                        <?php if ($cert['credential_url']): ?>
                                            <p class="mb-1">
                                                <small><a href="<?php echo htmlspecialchars($cert['credential_url']); ?>" target="_blank">
                                                    <i class="fas fa-external-link-alt me-1"></i>Verify Certificate
                                                </a></small>
                                            </p>
                                        <?php endif; ?>
                                        <?php if ($cert['file_path']): ?>
                                            <p class="mb-1">
                                                <small><a href="../uploads/certificates/<?php echo $cert['file_path']; ?>" target="_blank">
                                                    <i class="fas fa-download me-1"></i>View Certificate
                                                </a></small>
                                            </p>
                                        <?php endif; ?>
                                        <?php if ($cert['description']): ?>
                                            <p class="mb-0"><small><?php echo nl2br(htmlspecialchars($cert['description'])); ?></small></p>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>

                                <form method="POST" enctype="multipart/form-data" class="mt-3 no-print">
                                    <input type="hidden" name="action" value="add_certificate">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="cert_title" placeholder="Certificate Title *" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="cert_organization" placeholder="Issuing Organization *" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Issue Date</label>
                                            <input type="date" class="form-control" name="cert_issue_date">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Expiry Date</label>
                                            <input type="date" class="form-control" name="cert_expiry_date">
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <input type="text" class="form-control" name="credential_id" placeholder="Credential ID">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <input type="url" class="form-control" name="credential_url" placeholder="Verification URL">
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <textarea class="form-control" name="cert_description" rows="2" placeholder="Description (optional)"></textarea>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Certificate File (PDF/Image)</label>
                                        <input type="file" class="form-control" name="cert_file" accept=".pdf,.jpg,.jpeg,.png,.gif">
                                        <div class="form-text">Upload certificate copy (optional)</div>
                                    </div>
                                    <button type="submit" class="btn btn-success btn-sm">
                                        <i class="fas fa-plus me-1"></i>Add Certificate
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Document Upload Section -->
                    <div class="cv-section">
                        <h4><i class="fas fa-upload me-2"></i>Document Uploads</h4>
                        
                        <div class="row mb-4">
                            <?php foreach ($documents as $doc): ?>
                                <div class="col-md-4 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <h6 class="card-title">
                                                <i class="fas fa-file me-2"></i><?php echo htmlspecialchars($doc['title']); ?>
                                            </h6>
                                            <p class="card-text">
                                                <span class="badge bg-secondary"><?php echo ucfirst($doc['document_type']); ?></span>
                                                <br><small class="text-muted">
                                                    Size: <?php echo round($doc['file_size'] / 1024, 1); ?>KB
                                                    <br>Uploaded: <?php echo formatDate($doc['created_at']); ?>
                                                </small>
                                            </p>
                                            <?php if ($doc['description']): ?>
                                                <p class="card-text"><small><?php echo htmlspecialchars($doc['description']); ?></small></p>
                                            <?php endif; ?>
                                            <a href="../uploads/documents/<?php echo $doc['file_path']; ?>" target="_blank" class="btn btn-outline-primary btn-sm">
                                                <i class="fas fa-download me-1"></i>Download
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <form method="POST" enctype="multipart/form-data" class="no-print">
                            <input type="hidden" name="action" value="upload_document">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="document_type" class="form-label">Document Type *</label>
                                    <select class="form-select" name="document_type" required>
                                        <option value="">Select Type</option>
                                        <option value="cv">CV/Resume</option>
                                        <option value="cover_letter">Cover Letter</option>
                                        <option value="certificate">Certificate</option>
                                        <option value="transcript">Academic Transcript</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="doc_title" class="form-label">Document Title *</label>
                                    <input type="text" class="form-control" name="doc_title" placeholder="e.g., My Resume 2024" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="document" class="form-label">Choose File *</label>
                                <input type="file" class="form-control" name="document" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" required>
                                <div class="form-text">Supported formats: PDF, Word documents, Images (Max 5MB)</div>
                            </div>
                            <div class="mb-3">
                                <textarea class="form-control" name="doc_description" rows="2" placeholder="Document description (optional)"></textarea>
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_public" checked>
                                    <label class="form-check-label">
                                        Make visible to employers
                                    </label>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-upload me-1"></i>Upload Document
                            </button>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Edit Education Modal -->
    <div class="modal fade" id="editEducationModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Education</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="editEducationForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit_education">
                        <input type="hidden" name="edu_id" id="edit_edu_id">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <input type="text" class="form-control" name="institution" id="edit_institution" placeholder="Institution *" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <input type="text" class="form-control" name="degree" id="edit_degree" placeholder="Degree *" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <input type="text" class="form-control" name="field_of_study" id="edit_field_of_study" placeholder="Field of Study">
                            </div>
                            <div class="col-md-6 mb-3">
                                <input type="text" class="form-control" name="grade" id="edit_grade" placeholder="Grade/GPA">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Start Date</label>
                                <input type="date" class="form-control" name="start_date" id="edit_start_date">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">End Date</label>
                                <input type="date" class="form-control" name="end_date" id="edit_end_date">
                            </div>
                        </div>
                        <div class="mb-3">
                            <textarea class="form-control" name="description" id="edit_description" rows="3" placeholder="Description (optional)"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Education</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Experience Modal -->
    <div class="modal fade" id="editExperienceModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Work Experience</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="editExperienceForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit_experience">
                        <input type="hidden" name="exp_id" id="edit_exp_id">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <input type="text" class="form-control" name="company_name" id="edit_company_name" placeholder="Company Name *" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <input type="text" class="form-control" name="position" id="edit_position" placeholder="Position/Title *" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-5 mb-3">
                                <label class="form-label">Start Date</label>
                                <input type="date" class="form-control" name="start_date" id="edit_exp_start_date">
                            </div>
                            <div class="col-md-5 mb-3">
                                <label class="form-label">End Date</label>
                                <input type="date" class="form-control" name="end_date" id="edit_exp_end_date">
                            </div>
                            <div class="col-md-2 mb-3">
                                <label class="form-label">&nbsp;</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_current" id="edit_is_current">
                                    <label class="form-check-label" for="edit_is_current">Current</label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <textarea class="form-control" name="description" id="edit_exp_description" rows="4" placeholder="Job description and achievements..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Experience</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-save form data to localStorage
        document.addEventListener('DOMContentLoaded', function() {
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                const inputs = form.querySelectorAll('input, textarea, select');
                inputs.forEach(input => {
                    // Load saved data
                    const savedValue = localStorage.getItem('cv_' + input.name);
                    if (savedValue && input.type !== 'file') {
                        input.value = savedValue;
                    }
                    
                    // Save data on change
                    input.addEventListener('input', function() {
                        localStorage.setItem('cv_' + input.name, input.value);
                    });
                });
            });
        });
        
        // Clear localStorage on successful form submission
        document.addEventListener('DOMContentLoaded', function() {
            const successAlert = document.querySelector('.alert-success');
            if (successAlert) {
                localStorage.clear();
            }
        });

        // Education data for editing
        const educationData = <?php echo json_encode($education_records); ?>;
        
        // Experience data for editing
        const experienceData = <?php echo json_encode($experience_records); ?>;

        function editEducation(eduId) {
            const edu = educationData.find(e => e.id == eduId);
            if (edu) {
                document.getElementById('edit_edu_id').value = edu.id;
                document.getElementById('edit_institution').value = edu.institution;
                document.getElementById('edit_degree').value = edu.degree;
                document.getElementById('edit_field_of_study').value = edu.field_of_study || '';
                document.getElementById('edit_grade').value = edu.grade || '';
                document.getElementById('edit_start_date').value = edu.start_date || '';
                document.getElementById('edit_end_date').value = edu.end_date || '';
                document.getElementById('edit_description').value = edu.description || '';
                
                const modal = new bootstrap.Modal(document.getElementById('editEducationModal'));
                modal.show();
            }
        }

        function deleteEducation(eduId) {
            if (confirm('Are you sure you want to delete this education record?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.style.display = 'none';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'delete_education';
                
                const idInput = document.createElement('input');
                idInput.type = 'hidden';
                idInput.name = 'edu_id';
                idInput.value = eduId;
                
                form.appendChild(actionInput);
                form.appendChild(idInput);
                document.body.appendChild(form);
                form.submit();
            }
        }

        function editExperience(expId) {
            const exp = experienceData.find(e => e.id == expId);
            if (exp) {
                document.getElementById('edit_exp_id').value = exp.id;
                document.getElementById('edit_company_name').value = exp.company_name;
                document.getElementById('edit_position').value = exp.position;
                document.getElementById('edit_exp_start_date').value = exp.start_date || '';
                document.getElementById('edit_exp_end_date').value = exp.end_date || '';
                document.getElementById('edit_is_current').checked = exp.is_current == 1;
                document.getElementById('edit_exp_description').value = exp.description || '';
                
                const modal = new bootstrap.Modal(document.getElementById('editExperienceModal'));
                modal.show();
            }
        }

        function deleteExperience(expId) {
            if (confirm('Are you sure you want to delete this work experience record?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.style.display = 'none';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'delete_experience';
                
                const idInput = document.createElement('input');
                idInput.type = 'hidden';
                idInput.name = 'exp_id';
                idInput.value = expId;
                
                form.appendChild(actionInput);
                form.appendChild(idInput);
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>