<?php
require_once 'config/config.php';
// Include scoring functions if they exist
if (file_exists('includes/scoring_functions.php')) {
    require_once 'includes/scoring_functions.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 with visibility check
$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 j.status != 'closed' AND c.status = 'approved'
");
$stmt->execute([$job_id]);
$job = $stmt->fetch();

if ($job) {
    // Check if user can see this job based on visibility rules
    $can_view_job = false;
    
    // Company users can always view their own jobs (for "View Public Page" functionality)
    if (isLoggedIn('company') && isset($_SESSION['company_id']) && $_SESSION['company_id'] == $job['company_id']) {
        $can_view_job = true;
    } elseif (isLoggedIn('candidate')) {
        $stmt = $db->prepare("SELECT candidate_type, company_id FROM candidates WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $candidate_data = $stmt->fetch();
        
        if ($candidate_data && $candidate_data['candidate_type'] === 'internal') {
            // Internal candidates can see:
            // 1. Internal and 'both' jobs from their company
            // 2. External and 'both' jobs from OTHER companies (not their own)
            // They CANNOT see external-only jobs from their own company
            if ((in_array($job['job_visibility'], ['internal', 'both']) && $job['company_id'] == $candidate_data['company_id']) ||
                (in_array($job['job_visibility'], ['external', 'both']) && $job['company_id'] != $candidate_data['company_id'])) {
                $can_view_job = true;
            }
        } else {
            // External candidates can only see external and 'both' jobs
            if (in_array($job['job_visibility'], ['external', 'both'])) {
                $can_view_job = true;
            }
        }
    } else {
        // Non-logged in users can only see external and 'both' jobs
        if (in_array($job['job_visibility'], ['external', 'both'])) {
            $can_view_job = true;
        }
    }
    
    // If user cannot view this job, redirect or show error
    if (!$can_view_job) {
        $job = null; // This will trigger the redirect below
    }
}

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

// 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 ($job['status'] === 'closed') {
        $error = 'This job position is no longer accepting applications.';
    } elseif ($job['deadline'] && date('Y-m-d') > $job['deadline']) {
        $error = 'The application deadline for this job has passed.';
    } 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 {
                // Check candidate type and approval status
                $stmt = $db->prepare("SELECT candidate_type, hr_approval_status, company_id FROM candidates WHERE id = ?");
                $stmt->execute([$_SESSION['user_id']]);
                $candidate_data = $stmt->fetch();
                
                $is_internal = ($candidate_data['candidate_type'] === 'internal');
                $company_approved = ($candidate_data['hr_approval_status'] === 'approved');
                
                if ($is_internal && !$company_approved) {
                    $error = 'Internal employees must have company approval before applying for jobs. Please contact your company\'s HR department.';
                } elseif ($is_internal && $candidate_data['company_id'] != $job['company_id'] && $job['job_visibility'] !== 'both') {
                    $error = 'Internal employees can only apply for jobs within their own company or jobs marked as "both".';
                } else {
                    // Additional check: verify job visibility allows this candidate type
                    $can_apply = false;
                    if ($candidate_data['candidate_type'] === 'internal') {
                        // Internal candidates can apply to:
                        // 1. Internal jobs from their company
                        // 2. All external and 'both' jobs (from any company)
                        if (($job['job_visibility'] === 'internal' && $job['company_id'] == $candidate_data['company_id']) ||
                            (in_array($job['job_visibility'], ['external', 'both']))) {
                            $can_apply = true;
                        }
                    } else {
                        // External candidates can apply to external and 'both' jobs
                        if (in_array($job['job_visibility'], ['external', 'both'])) {
                            $can_apply = true;
                        }
                    }
                    
                    if (!$can_apply) {
                        $error = 'You are not eligible to apply for this position due to job visibility restrictions.';
                    } else {
                        // Insert application (trigger will automatically set hr_approval_required and status)
                        $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 and calculate weighted scores
                $total_weighted_score = 0;
                $question_count = 0;
                
                if (!empty($survey_questions) && function_exists('getResponseScore')) {
                    foreach ($survey_questions as $question) {
                        $response_key = 'survey_' . $question['id'];
                        $response = isset($_POST[$response_key]) ? $_POST[$response_key] : '';
                        $weight = (float)($question['weight'] ?? 0);
                        
                        $response_text = '';
                        // Handle array responses (checkboxes)
                        if (is_array($response)) {
                            $response_text = implode(', ', $response);
                        } else {
                            $response_text = (string)$response;
                        }
                        
                        // Always insert survey response (even if empty) to maintain consistency
                        $stmt = $db->prepare("
                            INSERT INTO job_application_survey_responses (application_id, question_id, response)
                            VALUES (?, ?, ?)
                        ");
                        $stmt->execute([$application_id, $question['id'], sanitize($response_text)]);
                        
                        // Calculate weighted score for this response
                        $response_score = getResponseScore($response_text, $question['question_type']);
                        $weighted_score = calculateWeightedScore($response_score, $weight);
                        $total_weighted_score += $weighted_score;
                        $question_count++;
                        
                        // Store the calculated score
                        $stmt = $db->prepare("
                            INSERT INTO application_scores (application_id, question_id, response_text, score_earned, weight_applied, weighted_score)
                            VALUES (?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([$application_id, $question['id'], sanitize($response_text), $response_score, $weight, $weighted_score]);
                    }
                    
                    // Update application with total weighted score (should equal final percentage since weights total 100%)
                    $stmt = $db->prepare("UPDATE job_applications SET total_score = ? WHERE id = ?");
                    $stmt->execute([round($total_weighted_score, 2), $application_id]);
                }
                
                        if ($is_internal) {
                            $success = 'Application submitted successfully! As an internal candidate, your application is pending HR approval for this position.';
                        } else {
                            $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>
    <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>

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

                        <!-- 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 ($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 elseif ($job['status'] === 'closed'): ?>
                            <div class="alert alert-warning">
                                <i class="fas fa-times-circle me-2"></i>This job position is no longer accepting applications.
                            </div>
                            <p class="text-muted">This job has been closed by the employer.</p>
                            <a href="jobs.php" class="btn btn-outline-primary">Browse Other Jobs</a>
                        <?php elseif ($job['deadline'] && date('Y-m-d') > $job['deadline']): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-calendar-times me-2"></i>Application deadline has passed.
                            </div>
                            <p class="text-muted">This job's application deadline was <?php echo formatDate($job['deadline']); ?>.</p>
                            <a href="jobs.php" class="btn btn-outline-primary">Browse Other Jobs</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>