<?php
require_once 'config/config.php';

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

$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$error = '';
$success = '';

if (!$job_id) {
    redirect('jobs.php');
}

// Get job details
$stmt = $db->prepare("
    SELECT j.*, c.name as company_name, c.email as company_email, 
           c.phone as company_phone, c.website as company_website,
           c.description as company_description, c.logo as company_logo,
           cat.name as category_name
    FROM jobs j 
    JOIN companies c ON j.company_id = c.id 
    LEFT JOIN job_categories cat ON j.category_id = cat.id 
    WHERE j.id = ? AND j.status = 'active' AND c.status = 'approved'
");
$stmt->execute([$job_id]);
$job = $stmt->fetch();

if (!$job) {
    redirect('jobs.php');
}

// Get job benefits
$stmt = $db->prepare("
    SELECT jb.* FROM job_benefits jb
    JOIN job_benefit_selections jbs ON jb.id = jbs.benefit_id
    WHERE jbs.job_id = ? AND jb.is_active = 1
    ORDER BY jb.display_order, jb.name
");
$stmt->execute([$job_id]);
$job_benefits = $stmt->fetchAll();

// Check if candidate can access this job based on job type
$can_access_job = true;
$access_error = '';

if (isLoggedIn('candidate')) {
    $stmt = $db->prepare("SELECT candidate_type, company_id, employment_status, approval_status FROM candidates WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $candidate_info = $stmt->fetch();
    
    if ($candidate_info) {
        $user_candidate_type = $candidate_info['candidate_type'];
        $user_company_id = $candidate_info['company_id'];
        $employment_status = $candidate_info['employment_status'];
        $approval_status = $candidate_info['approval_status'];
        
        if ($job['job_type'] === 'internal') {
            // Internal jobs are only for active, approved internal candidates from the same company
            if ($user_candidate_type !== 'internal' || $user_company_id != $job['company_id']) {
                $can_access_job = false;
                $access_error = 'This job is only available for internal candidates from ' . $job['company_name'] . '.';
            } elseif ($employment_status !== 'active' || $approval_status !== 'approved') {
                $can_access_job = false;
                if ($employment_status === 'inactive') {
                    $access_error = 'Your employment status is currently inactive. You cannot access internal job postings at this time.';
                } elseif ($employment_status === 'terminated') {
                    $access_error = 'Your employment has been terminated. You no longer have access to internal job postings.';
                } else {
                    $access_error = 'Your internal candidate application is pending approval. You cannot access internal job postings yet.';
                }
            }
        } elseif ($job['job_type'] === 'external') {
            // External jobs are only for external candidates
            if ($user_candidate_type !== 'external') {
                $can_access_job = false;
                $access_error = 'This job is only available for external candidates.';
            }
        } elseif ($job['job_type'] === 'both') {
            // For 'both' type jobs, internal candidates still need to be active and approved
            if ($user_candidate_type === 'internal' && ($employment_status !== 'active' || $approval_status !== 'approved')) {
                // Internal candidates who are not active/approved can still see the job but as external candidates
                // No access restriction, but they would apply as external
            }
        }
    }
} else {
    // Non-logged users can only access external or both jobs
    if ($job['job_type'] === 'internal') {
        $can_access_job = false;
        $access_error = 'This job requires login as an internal candidate.';
    }
}

if (!$can_access_job) {
    $error = $access_error;
}

// Check if user already applied
$has_applied = false;
$application = null;

if (isLoggedIn('candidate')) {
    $stmt = $db->prepare("SELECT * FROM job_applications WHERE job_id = ? AND candidate_id = ?");
    $stmt->execute([$job_id, $_SESSION['user_id']]);
    $application = $stmt->fetch();
    $has_applied = (bool)$application;
}

// Get candidate's resumes if logged in
$resumes = [];
if (isLoggedIn('candidate')) {
    $stmt = $db->prepare("SELECT * FROM resumes WHERE candidate_id = ? ORDER BY is_primary DESC, created_at DESC");
    $stmt->execute([$_SESSION['user_id']]);
    $resumes = $stmt->fetchAll();
}

// Get survey questions for this job
$survey_questions = [];
$stmt = $db->prepare("SELECT * FROM job_survey_questions WHERE job_id = ? ORDER BY question_order ASC");
$stmt->execute([$job_id]);
$survey_questions = $stmt->fetchAll();

// Handle job application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply'])) {
    if (!isLoggedIn('candidate')) {
        $error = 'Please login as a candidate to apply for jobs.';
    } elseif ($has_applied) {
        $error = 'You have already applied for this job.';
    } elseif (!$can_access_job) {
        $error = $access_error;
    } else {
        $resume_id = isset($_POST['resume_id']) ? (int)$_POST['resume_id'] : null;
        $cover_letter = sanitize($_POST['cover_letter']);
        
        // Validate survey questions
        $survey_errors = [];
        if (!empty($survey_questions)) {
            foreach ($survey_questions as $question) {
                $response_key = 'survey_' . $question['id'];
                $response = isset($_POST[$response_key]) ? $_POST[$response_key] : '';
                
                if ($question['is_required'] && empty($response)) {
                    $survey_errors[] = "Please answer: " . htmlspecialchars($question['question']);
                }
            }
        }
        
        if (empty($cover_letter)) {
            $error = 'Cover letter is required.';
        } elseif (!empty($survey_errors)) {
            $error = implode('<br>', $survey_errors);
        } else {
            try {
                // Insert application
                $stmt = $db->prepare("
                    INSERT INTO job_applications (job_id, candidate_id, resume_id, cover_letter) 
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$job_id, $_SESSION['user_id'], $resume_id, $cover_letter]);
                
                $application_id = $db->lastInsertId();
                
                // Insert survey responses
                if (!empty($survey_questions)) {
                    foreach ($survey_questions as $question) {
                        $response_key = 'survey_' . $question['id'];
                        $response = isset($_POST[$response_key]) ? $_POST[$response_key] : '';
                        
                        if (!empty($response)) {
                            // Handle array responses (checkboxes)
                            if (is_array($response)) {
                                $response = implode(', ', $response);
                            }
                            
                            $stmt = $db->prepare("
                                INSERT INTO job_application_survey_responses (application_id, question_id, response)
                                VALUES (?, ?, ?)
                            ");
                            $stmt->execute([$application_id, $question['id'], sanitize($response)]);
                        }
                    }
                }
                
                $success = 'Application submitted successfully!';
                $has_applied = true;
                
                // Get the new application
                $stmt = $db->prepare("SELECT * FROM job_applications WHERE job_id = ? AND candidate_id = ?");
                $stmt->execute([$job_id, $_SESSION['user_id']]);
                $application = $stmt->fetch();
                
            } catch (PDOException $e) {
                $error = 'Error submitting application. Please try again.';
            }
        }
    }
}

// Get similar jobs
$stmt = $db->prepare("
    SELECT j.*, c.name as company_name, cat.name as category_name
    FROM jobs j 
    JOIN companies c ON j.company_id = c.id 
    LEFT JOIN job_categories cat ON j.category_id = cat.id 
    WHERE j.id != ? AND j.status = 'active' AND c.status = 'approved'
    AND (j.category_id = ? OR j.location LIKE ?)
    ORDER BY j.created_at DESC 
    LIMIT 3
");
$stmt->execute([$job_id, $job['category_id'], '%' . $job['location'] . '%']);
$similar_jobs = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($job['title']); ?> - <?php echo SITE_NAME; ?></title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="assets/images/favicon.ico">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/images/favicon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="assets/images/favicon-16x16.png">
    <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">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="jobs.php">Browse Jobs</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="companies.php">Companies</a>
                    </li>
                </ul>
                
                <ul class="navbar-nav">
                    <?php if (isLoggedIn()): ?>
                        <?php if ($_SESSION['user_type'] === 'admin'): ?>
                            <li class="nav-item">
                                <a class="nav-link" href="admin/dashboard.php">Admin Dashboard</a>
                            </li>
                        <?php elseif ($_SESSION['user_type'] === 'company'): ?>
                            <li class="nav-item">
                                <a class="nav-link" href="company/dashboard.php">Company Dashboard</a>
                            </li>
                        <?php elseif ($_SESSION['user_type'] === 'candidate'): ?>
                            <li class="nav-item">
                                <a class="nav-link" href="candidate/dashboard.php">My Profile</a>
                            </li>
                        <?php endif; ?>
                        <li class="nav-item">
                            <a class="nav-link" href="auth/logout.php">Logout</a>
                        </li>
                    <?php else: ?>
                        <li class="nav-item">
                            <a class="nav-link" href="auth/login.php">Login</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="auth/register.php">Register</a>
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                <li class="breadcrumb-item"><a href="jobs.php">Jobs</a></li>
                <li class="breadcrumb-item active"><?php echo htmlspecialchars($job['title']); ?></li>
            </ol>
        </nav>

        <?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; ?>

        <div class="row">
            <!-- Job Details -->
            <div class="col-lg-8 mb-4">
                <div class="card">
                    <div class="card-body">
                        <!-- Job Header -->
                        <div class="d-flex align-items-start mb-4">
                            <div class="company-logo me-3">
                                <?php if ($job['company_logo']): ?>
                                    <img src="<?php echo UPLOAD_URL . 'logos/' . $job['company_logo']; ?>" 
                                         alt="Company Logo" class="company-logo">
                                <?php else: ?>
                                    <div class="company-logo bg-light d-flex align-items-center justify-content-center">
                                        <i class="fas fa-building text-muted fa-2x"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="flex-grow-1">
                                <h1 class="h3 mb-2"><?php echo htmlspecialchars($job['title']); ?></h1>
                                <h5 class="text-primary mb-3"><?php echo htmlspecialchars($job['company_name']); ?></h5>
                                
                                <div class="row g-3 mb-3">
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-map-marker-alt me-1"></i>Location
                                        </small>
                                        <span><?php echo htmlspecialchars($job['location']); ?></span>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-briefcase me-1"></i>Employment Type
                                        </small>
                                        <span><?php echo ucfirst(str_replace('-', ' ', $job['employment_type'])); ?></span>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-layer-group me-1"></i>Experience Level
                                        </small>
                                        <span><?php echo ucfirst($job['experience_level']); ?> Level</span>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-tag me-1"></i>Category
                                        </small>
                                        <span><?php echo htmlspecialchars($job['category_name']); ?></span>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-users me-1"></i>Job Type
                                        </small>
                                        <?php
                                        $job_type_badge = '';
                                        $job_type_icon = '';
                                        switch ($job['job_type']) {
                                            case 'internal':
                                                $job_type_badge = 'bg-warning text-dark';
                                                $job_type_icon = 'fas fa-user-tie';
                                                $job_type_text = 'Internal Only';
                                                break;
                                            case 'external':
                                                $job_type_badge = 'bg-info text-white';
                                                $job_type_icon = 'fas fa-globe';
                                                $job_type_text = 'External Only';
                                                break;
                                            default:
                                                $job_type_badge = 'bg-primary text-white';
                                                $job_type_icon = 'fas fa-users';
                                                $job_type_text = 'All Candidates';
                                        }
                                        ?>
                                        <span class="badge <?php echo $job_type_badge; ?>">
                                            <i class="<?php echo $job_type_icon; ?> me-1"></i>
                                            <?php echo $job_type_text; ?>
                                        </span>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-map-marker-alt me-1"></i>Work Location
                                        </small>
                                        <?php
                                        $work_location_badge = '';
                                        $work_location_icon = '';
                                        switch ($job['work_location_type']) {
                                            case 'remote':
                                                $work_location_badge = 'bg-success text-white';
                                                $work_location_icon = 'fas fa-home';
                                                $work_location_text = 'Work from Home';
                                                break;
                                            case 'hybrid':
                                                $work_location_badge = 'bg-warning text-dark';
                                                $work_location_icon = 'fas fa-arrows-alt-h';
                                                $work_location_text = 'Hybrid (Office + Remote)';
                                                break;
                                            default:
                                                $work_location_badge = 'bg-secondary text-white';
                                                $work_location_icon = 'fas fa-building';
                                                $work_location_text = 'Office-based';
                                        }
                                        ?>
                                        <span class="badge <?php echo $work_location_badge; ?>">
                                            <i class="<?php echo $work_location_icon; ?> me-1"></i>
                                            <?php echo $work_location_text; ?>
                                        </span>
                                    </div>
                                </div>

                                <?php if ($job['salary_min'] || $job['salary_max']): ?>
                                    <div class="mb-3">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-coins me-1"></i>Salary Range
                                        </small>
                                        <span class="h5 text-success">
                                            <?php if ($job['salary_min'] && $job['salary_max']): ?>
                                                R<?php echo number_format($job['salary_min']); ?> - R<?php echo number_format($job['salary_max']); ?>
                                            <?php elseif ($job['salary_min']): ?>
                                                From R<?php echo number_format($job['salary_min']); ?>
                                            <?php else: ?>
                                                Up to R<?php echo number_format($job['salary_max']); ?>
                                            <?php endif; ?>
                                        </span>
                                    </div>
                                <?php endif; ?>

                                <?php if ($job['deadline']): ?>
                                    <div class="mb-3">
                                        <small class="text-muted d-block">
                                            <i class="fas fa-calendar-alt me-1"></i>Application Deadline
                                        </small>
                                        <span><?php echo formatDate($job['deadline']); ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Job Description -->
                        <div class="mb-4">
                            <h4>Job Description</h4>
                            <div class="content">
                                <?php echo nl2br(htmlspecialchars($job['description'])); ?>
                            </div>
                        </div>

                        <!-- Requirements -->
                        <?php if ($job['requirements']): ?>
                            <div class="mb-4">
                                <h4>Requirements & Qualifications</h4>
                                <div class="content">
                                    <?php echo nl2br(htmlspecialchars($job['requirements'])); ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Job Benefits -->
                        <?php if (!empty($job_benefits)): ?>
                            <div class="mb-4">
                                <h4>Benefits & Perks</h4>
                                <div class="row">
                                    <?php foreach ($job_benefits as $benefit): ?>
                                        <div class="col-md-6 col-lg-4 mb-3">
                                            <div class="benefit-item d-flex align-items-start">
                                                <div class="benefit-icon me-3">
                                                    <i class="<?php echo $benefit['icon']; ?> fa-lg text-primary"></i>
                                                </div>
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($benefit['name']); ?></h6>
                                                    <?php if ($benefit['description']): ?>
                                                        <small class="text-muted"><?php echo htmlspecialchars($benefit['description']); ?></small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Company Information -->
                        <div class="mb-4">
                            <h4>About <?php echo htmlspecialchars($job['company_name']); ?></h4>
                            <?php if ($job['company_description']): ?>
                                <p><?php echo nl2br(htmlspecialchars($job['company_description'])); ?></p>
                            <?php endif; ?>
                            
                            <div class="row">
                                <?php if ($job['company_website']): ?>
                                    <div class="col-md-6 mb-2">
                                        <small class="text-muted">Website:</small><br>
                                        <a href="<?php echo htmlspecialchars($job['company_website']); ?>" target="_blank">
                                            <?php echo htmlspecialchars($job['company_website']); ?>
                                        </a>
                                    </div>
                                <?php endif; ?>
                                <?php if ($job['company_phone']): ?>
                                    <div class="col-md-6 mb-2">
                                        <small class="text-muted">Phone:</small><br>
                                        <?php echo htmlspecialchars($job['company_phone']); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>


                        <div class="border-top pt-3">
                            <small class="text-muted">
                                Posted on <?php echo formatDate($job['created_at']); ?>
                            </small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Application Sidebar -->
            <div class="col-lg-4">
                <!-- Application Form -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-paper-plane me-2"></i>Apply for this Job
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (!isLoggedIn()): ?>
                            <p class="text-muted mb-3">Please login to apply for this job.</p>
                            <div class="d-grid gap-2">
                                <a href="auth/login.php" class="btn btn-primary">Login</a>
                                <a href="auth/register.php?type=candidate" class="btn btn-outline-primary">Register as Candidate</a>
                            </div>
                        <?php elseif ($_SESSION['user_type'] !== 'candidate'): ?>
                            <p class="text-muted">Only candidates can apply for jobs.</p>
                            <a href="auth/register.php?type=candidate" class="btn btn-outline-primary">Register as Candidate</a>
                        <?php elseif (!$can_access_job): ?>
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($access_error); ?>
                            </div>
                            <?php if ($job['job_type'] === 'internal' && !isLoggedIn('candidate')): ?>
                                <div class="d-grid">
                                    <a href="auth/login.php" class="btn btn-primary">Login as Internal Candidate</a>
                                </div>
                            <?php endif; ?>
                        <?php elseif ($has_applied): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i>You have already applied for this job.
                            </div>
                            <div class="mb-3">
                                <strong>Application Status:</strong>
                                <span class="badge status-<?php echo $application['status']; ?> ms-2">
                                    <?php echo ucfirst($application['status']); ?>
                                </span>
                            </div>
                            <div class="mb-3">
                                <strong>Applied on:</strong> <?php echo formatDate($application['applied_at']); ?>
                            </div>
                            <a href="candidate/applications.php" class="btn btn-outline-primary">View My Applications</a>
                        <?php else: ?>
                            <form method="POST">
                                <?php if (!empty($resumes)): ?>
                                    <div class="mb-3">
                                        <label for="resume_id" class="form-label">Select Resume</label>
                                        <select class="form-select" id="resume_id" name="resume_id">
                                            <option value="">Choose a resume (optional)</option>
                                            <?php foreach ($resumes as $resume): ?>
                                                <option value="<?php echo $resume['id']; ?>" <?php echo $resume['is_primary'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($resume['title']); ?>
                                                    <?php echo $resume['is_primary'] ? ' (Primary)' : ''; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-info">
                                        <small>
                                            <i class="fas fa-info-circle me-1"></i>
                                            Consider <a href="candidate/cv-builder.php">building your CV</a> to improve your application.
                                        </small>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-3">
                                    <label for="cover_letter" class="form-label">Cover Letter *</label>
                                    <textarea class="form-control" id="cover_letter" name="cover_letter" rows="6" 
                                              placeholder="Write a compelling cover letter explaining why you're perfect for this role..." required></textarea>
                                </div>

                                <!-- Survey Questions -->
                                <?php if (!empty($survey_questions)): ?>
                                    <div class="mb-4">
                                        <h6 class="mb-3">Additional Questions</h6>
                                        <p class="text-muted small mb-3">Please answer the following questions to complete your application:</p>
                                        
                                        <?php foreach ($survey_questions as $question): ?>
                                            <div class="mb-3">
                                                <label class="form-label">
                                                    <?php echo htmlspecialchars($question['question']); ?>
                                                    <?php if ($question['is_required']): ?>
                                                        <span class="text-danger">*</span>
                                                    <?php endif; ?>
                                                </label>
                                                
                                                <?php 
                                                $field_name = 'survey_' . $question['id'];
                                                $options = $question['options'] ? json_decode($question['options'], true) : [];
                                                ?>
                                                
                                                <?php if ($question['question_type'] === 'text'): ?>
                                                    <input type="text" class="form-control" name="<?php echo $field_name; ?>" 
                                                           <?php echo $question['is_required'] ? 'required' : ''; ?>>
                                                           
                                                <?php elseif ($question['question_type'] === 'textarea'): ?>
                                                    <textarea class="form-control" name="<?php echo $field_name; ?>" rows="4" 
                                                              <?php echo $question['is_required'] ? 'required' : ''; ?>></textarea>
                                                              
                                                <?php elseif ($question['question_type'] === 'select'): ?>
                                                    <select class="form-select" name="<?php echo $field_name; ?>" 
                                                            <?php echo $question['is_required'] ? 'required' : ''; ?>>
                                                        <option value="">Choose an option...</option>
                                                        <?php foreach ($options as $option): ?>
                                                            <option value="<?php echo htmlspecialchars($option); ?>">
                                                                <?php echo htmlspecialchars($option); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    
                                                <?php elseif ($question['question_type'] === 'radio'): ?>
                                                    <?php foreach ($options as $index => $option): ?>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="radio" 
                                                                   name="<?php echo $field_name; ?>" 
                                                                   value="<?php echo htmlspecialchars($option); ?>"
                                                                   id="<?php echo $field_name . '_' . $index; ?>"
                                                                   <?php echo $question['is_required'] ? 'required' : ''; ?>>
                                                            <label class="form-check-label" for="<?php echo $field_name . '_' . $index; ?>">
                                                                <?php echo htmlspecialchars($option); ?>
                                                            </label>
                                                        </div>
                                                    <?php endforeach; ?>
                                                    
                                                <?php elseif ($question['question_type'] === 'checkbox'): ?>
                                                    <?php foreach ($options as $index => $option): ?>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" 
                                                                   name="<?php echo $field_name; ?>[]" 
                                                                   value="<?php echo htmlspecialchars($option); ?>"
                                                                   id="<?php echo $field_name . '_' . $index; ?>">
                                                            <label class="form-check-label" for="<?php echo $field_name . '_' . $index; ?>">
                                                                <?php echo htmlspecialchars($option); ?>
                                                            </label>
                                                        </div>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="d-grid">
                                    <button type="submit" name="apply" class="btn btn-primary">
                                        <i class="fas fa-paper-plane me-1"></i>Submit Application
                                    </button>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Similar Jobs -->
                <?php if (!empty($similar_jobs)): ?>
                    <div class="card">
                        <div class="card-header">
                            <h6 class="card-title mb-0">Similar Jobs</h6>
                        </div>
                        <div class="card-body">
                            <?php foreach ($similar_jobs as $similar_job): ?>
                                <div class="mb-3 pb-3 <?php echo $similar_job !== end($similar_jobs) ? 'border-bottom' : ''; ?>">
                                    <h6 class="mb-1">
                                        <a href="job-details.php?id=<?php echo $similar_job['id']; ?>" class="text-decoration-none">
                                            <?php echo htmlspecialchars($similar_job['title']); ?>
                                        </a>
                                    </h6>
                                    <small class="text-muted d-block"><?php echo htmlspecialchars($similar_job['company_name']); ?></small>
                                    <small class="text-muted"><?php echo htmlspecialchars($similar_job['location']); ?></small>
                                </div>
                            <?php endforeach; ?>
                            <a href="jobs.php?category=<?php echo $job['category_id']; ?>" class="btn btn-sm btn-outline-primary w-100">
                                View More Jobs
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-lg-6">
                    <h5><?php echo SITE_NAME; ?></h5>
                    <p class="text-muted">Connecting talented individuals with amazing opportunities.</p>
                </div>
                <div class="col-lg-6">
                    <div class="text-lg-end">
                        <p>&copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. All rights reserved.</p>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>