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

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

// Pagination setup
$items_per_page = 4;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $items_per_page;

// Get recent jobs for display (with visibility filtering)
$job_visibility_filter = "j.job_visibility IN ('external', 'both')";
$job_params = [];

// If user is logged in as internal candidate, show their company's internal jobs too
if (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') {
        $job_visibility_filter = "(
            (j.job_visibility = 'internal' AND j.company_id = ?) OR 
            (j.job_visibility = 'both' AND j.company_id = ?) OR 
            (j.job_visibility IN ('external', 'both') AND j.company_id != ?)
        )";
        $job_params = [$candidate_data['company_id'], $candidate_data['company_id'], $candidate_data['company_id']];
    }
}

// Count total jobs for pagination
$count_query = "
    SELECT COUNT(*) as total 
    FROM jobs j 
    LEFT JOIN companies c ON j.company_id = c.id 
    WHERE j.status = 'active' AND c.status = 'approved' AND (j.deadline IS NULL OR j.deadline >= CURDATE()) AND $job_visibility_filter
";
$stmt = $db->prepare($count_query);
$stmt->execute($job_params);
$total_jobs = $stmt->fetch()['total'];
$total_pages = ceil($total_jobs / $items_per_page);

// Get jobs for current page
$stmt = $db->prepare("
    SELECT j.*, c.name as company_name, c.logo as company_logo, cat.name as category_name 
    FROM jobs j 
    LEFT JOIN companies c ON j.company_id = c.id 
    LEFT JOIN job_categories cat ON j.category_id = cat.id 
    WHERE j.status = 'active' AND c.status = 'approved' AND (j.deadline IS NULL OR j.deadline >= CURDATE()) AND $job_visibility_filter
    ORDER BY j.created_at DESC 
    LIMIT $items_per_page OFFSET $offset
");
$stmt->execute($job_params);
$recent_jobs = $stmt->fetchAll();

// Get job categories
$stmt = $db->prepare("SELECT * FROM job_categories ORDER BY name");
$stmt->execute();
$categories = $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 SITE_NAME; ?> - Find Your Dream Job</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>
        /* Job Cards - Modern List Style (from jobs.php) */
        .job-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            position: relative;
            text-decoration: none;
            color: inherit;
            display: block;
        }
        
        .job-card:hover {
            border-color: #FFA500;
            box-shadow: 0 4px 12px rgba(255, 165, 0, 0.1);
            transform: translateY(-2px);
            text-decoration: none;
            color: inherit;
        }
        
        .job-header {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .company-logo {
            width: 60px;
            height: 60px;
            object-fit: contain;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            background: white;
            padding: 6px;
            flex-shrink: 0;
        }
        
        .company-logo-placeholder {
            width: 60px;
            height: 60px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            flex-shrink: 0;
        }
        
        .job-info {
            flex-grow: 1;
            min-width: 0;
        }
        
        .job-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #2d3748;
            margin: 0 0 0.25rem 0;
            line-height: 1.4;
        }
        
        .job-card:hover .job-title {
            color: #FFA500;
        }
        
        .company-name {
            color: #718096;
            font-size: 0.95rem;
            margin: 0 0 0.5rem 0;
        }
        
        .job-location {
            color: #a0aec0;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .job-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }
        
        .job-badge {
            background: #f7fafc;
            color: #4a5568;
            border: 1px solid #e2e8f0;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.8rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .job-badge.remote {
            background: #fed7d7;
            color: #c53030;
            border-color: #feb2b2;
        }
        
        .job-badge.market-related {
            background: #c6f6d5;
            color: #22543d;
            border-color: #9ae6b4;
        }
        
        .job-badge.internal {
            background: #fed7d7;
            color: #c53030;
            border-color: #feb2b2;
        }
        
        .job-badge.external {
            background: #c6f6d5;
            color: #22543d;
            border-color: #9ae6b4;
        }
        
        .job-badge.both {
            background: #faf089;
            color: #744210;
            border-color: #ecc94b;
        }
        
        .job-posted {
            color: #a0aec0;
            font-size: 0.85rem;
            position: absolute;
            top: 1.5rem;
            right: 1.5rem;
        }
        
        .job-description {
            color: #4a5568;
            font-size: 0.9rem;
            line-height: 1.5;
            margin-bottom: 1rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        .jobs-container-home {
            max-width: 100%;
        }
        
        @media (min-width: 768px) {
            .jobs-container-home {
                max-width: 900px;
                margin: 0 auto;
            }
        }
        
        /* Pagination styling */
        .pagination .page-link {
            color: #FFA500;
            border-color: #dee2e6;
        }
        
        .pagination .page-link:hover {
            color: #ff8c00;
            background-color: #fff3cd;
            border-color: #FFA500;
        }
        
        .pagination .page-item.active .page-link {
            background-color: #FFA500;
            border-color: #FFA500;
            color: white;
        }
        
        .pagination .page-item.disabled .page-link {
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                
                <img src="assets\images\cefgroup.png" alt="sanpc logo" width="350" height="100">
            </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 active" 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>

    <!-- Hero Section -->
    <section class="hero-section text-white">
        <div class="container">
            <div class="row align-items-center min-vh-75">
                <div class="col-lg-8 mx-auto text-center hero-content">
                    <h1 class="display-3 fw-bold mb-4">Find Your Dream Job Today</h1>
                    <p class="lead mb-5 fs-4">Connect with top companies and discover amazing career opportunities that match your skills and aspirations in a modern, professional environment.</p>
                    <div class="d-flex flex-column flex-sm-row gap-3 justify-content-center">
                        <a href="jobs.php" class="btn btn-light btn-lg px-5 py-3">
                            <i class="fas fa-search me-2"></i>Browse Jobs
                        </a>
                        <a href="auth/register.php" class="btn btn-outline-light btn-lg px-5 py-3">
                            <i class="fas fa-user-plus me-2"></i>Join as Candidate
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Job Search Section -->
    <section class="py-5">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <div class="card shadow-sm">
                        <div class="card-body p-4">
                            <form action="jobs.php" method="GET">
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <input type="text" class="form-control" name="keyword" placeholder="Job title, skills...">
                                    </div>
                                    <div class="col-md-3">
                                        <select class="form-select" name="category">
                                            <option value="">All Categories</option>
                                            <?php foreach ($categories as $category): ?>
                                                <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" class="form-control" name="location" placeholder="Location">
                                    </div>
                                    <div class="col-md-2">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-search"></i> Search
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Recent Jobs Section -->
    <section class="py-5 bg-light">
        <div class="container">
            
            <div class="jobs-container-home">
                <?php if (empty($recent_jobs)): ?>
                    <div class="text-center py-5">
                        <div class="mb-4">
                            <i class="fas fa-briefcase fa-4x text-muted"></i>
                        </div>
                        <h4 class="text-muted mb-3">No Jobs Available</h4>
                        <p class="text-muted mb-4">There are currently no job opportunities available. Please check back later.</p>
                        <a href="jobs.php" class="btn btn-primary">Browse All Jobs</a>
                    </div>
                <?php else: ?>
                    <?php foreach ($recent_jobs as $job): ?>
                        <a href="job-details.php?id=<?php echo $job['id']; ?>" class="job-card">
                        <div class="job-posted">
                            <?php 
                            $days_ago = floor((time() - strtotime($job['created_at'])) / (60 * 60 * 24));
                            if ($days_ago == 0) {
                                echo "Today";
                            } elseif ($days_ago == 1) {
                                echo "1 day ago";
                            } else {
                                echo $days_ago . " days ago";
                            }
                            ?>
                        </div>
                        
                        <div class="job-header">
                            <!-- Company Logo -->
                            <div>
                                <?php if ($job['company_logo']): ?>
                                    <img src="<?php echo UPLOAD_URL . 'logos/' . $job['company_logo']; ?>" 
                                         alt="<?php echo htmlspecialchars($job['company_name']); ?>" 
                                         class="company-logo">
                                <?php else: ?>
                                    <div class="company-logo-placeholder">
                                        <i class="fas fa-building"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Job Info -->
                            <div class="job-info">
                                <h3 class="job-title"><?php echo htmlspecialchars($job['title']); ?></h3>
                                <div class="company-name"><?php echo htmlspecialchars($job['company_name']); ?></div>
                                <div class="job-location">
                                    <i class="fas fa-map-marker-alt"></i>
                                    <?php echo htmlspecialchars($job['location']); ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Job Description Preview -->
                        <div class="job-description">
                            <?php 
                            $description = strip_tags($job['description']);
                            echo htmlspecialchars(substr($description, 0, 150) . '...');
                            ?>
                        </div>
                        
                        <!-- Job Meta -->
                        <div class="job-meta">
                            <span class="job-badge">
                                <i class="fas fa-briefcase"></i>
                                <?php echo htmlspecialchars($job['category_name'] ?: 'General'); ?>
                            </span>
                            <span class="job-badge">
                                <i class="fas fa-clock"></i>
                                <?php echo ucfirst(str_replace('-', ' ', $job['employment_type'])); ?>
                            </span>
                            <span class="job-badge">
                                <i class="fas fa-layer-group"></i>
                                <?php echo ucfirst($job['experience_level']); ?> Level
                            </span>
                            
                            <?php if (strpos(strtolower($job['description']), 'remote') !== false): ?>
                                <span class="job-badge remote">
                                    <i class="fas fa-home"></i>
                                    Remote Work
                                </span>
                            <?php endif; ?>
                            
                            <?php if ($job['salary_min'] || $job['salary_max']): ?>
                                <span class="job-badge market-related">
                                    <i class="fas fa-coins"></i>
                                    <?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>
                            <?php endif; ?>
                            
                            <!-- Job Visibility Badge -->
                            <?php 
                            $visibility = $job['job_visibility'] ?? 'external'; // Default to external if not set
                            $visibility_class = strtolower($visibility);
                            $visibility_icon = '';
                            $visibility_text = '';
                            
                            switch($visibility) {
                                case 'internal':
                                    $visibility_icon = 'fas fa-building';
                                    $visibility_text = 'Internal Only';
                                    break;
                                case 'external':
                                    $visibility_icon = 'fas fa-globe';
                                    $visibility_text = 'External Only';
                                    break;
                                case 'both':
                                    $visibility_icon = 'fas fa-users';
                                    $visibility_text = 'Internal & External';
                                    break;
                                default:
                                    $visibility_icon = 'fas fa-globe';
                                    $visibility_text = 'External Only';
                            }
                            ?>
                            <span class="job-badge <?php echo $visibility_class; ?>">
                                <i class="<?php echo $visibility_icon; ?>"></i>
                                <?php echo $visibility_text; ?>
                            </span>
                        </div>
                    </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="d-flex justify-content-center mt-4">
                    <nav aria-label="Job pagination">
                        <ul class="pagination">
                            <!-- Previous Page -->
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                            <?php else: ?>
                                <li class="page-item disabled">
                                    <span class="page-link" aria-hidden="true">&laquo;</span>
                                </li>
                            <?php endif; ?>

                            <!-- Page Numbers -->
                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++): ?>
                                <?php if ($i == $page): ?>
                                    <li class="page-item active">
                                        <span class="page-link"><?php echo $i; ?></span>
                                    </li>
                                <?php else: ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                    </li>
                                <?php endif; ?>
                            <?php endfor; ?>

                            <!-- Next Page -->
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            <?php else: ?>
                                <li class="page-item disabled">
                                    <span class="page-link" aria-hidden="true">&raquo;</span>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
                
                <!-- Pagination Info -->
                <div class="text-center mt-3">
                    <small class="text-muted">
                        Showing <?php echo count($recent_jobs); ?> of <?php echo $total_jobs; ?> job<?php echo $total_jobs != 1 ? 's' : ''; ?>
                        (Page <?php echo $page; ?> of <?php echo $total_pages; ?>)
                    </small>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($recent_jobs)): ?>
                <div class="text-center mt-4">
                    <a href="jobs.php" class="btn btn-primary btn-lg">View All Jobs</a>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <!-- Features Section -->
    <section class="py-5">
        <div class="container">
            <div class="text-center mb-5">
                <h2 class="fw-bold">Why Choose Our Platform?</h2>
            </div>
            
            <div class="row">
                <div class="col-lg-4 col-md-6 mb-4">
                    <div class="text-center">
                        <div class="feature-icon bg-primary text-white rounded-circle mx-auto mb-3">
                            <i class="fas fa-search fa-2x"></i>
                        </div>
                        <h4>Easy Job Search</h4>
                        <p class="text-muted">Find the perfect job with our advanced search and filtering options.</p>
                    </div>
                </div>
                
                <div class="col-lg-4 col-md-6 mb-4">
                    <div class="text-center">
                        <div class="feature-icon bg-success text-white rounded-circle mx-auto mb-3">
                            <i class="fas fa-users fa-2x"></i>
                        </div>
                        <h4>Top Companies</h4>
                        <p class="text-muted">Connect with leading companies and employers in your industry.</p>
                    </div>
                </div>
                
                <div class="col-lg-4 col-md-6 mb-4">
                    <div class="text-center">
                        <div class="feature-icon bg-info text-white rounded-circle mx-auto mb-3">
                            <i class="fas fa-file-alt fa-2x"></i>
                        </div>
                        <h4>Online CV Builder</h4>
                        <p class="text-muted">Create professional resumes with our built-in CV builder tool.</p>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Footer -->
    <footer class="bg-dark text-white py-4">
        <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>
    <script>
        // Handle hero background image fallbacks for office team image
        document.addEventListener('DOMContentLoaded', function() {
            const heroSection = document.querySelector('.hero-section');
            if (heroSection) {
                // Test if hero-office-team.jpg loads successfully
                const testImage = new Image();
                testImage.onload = function() {
                    console.log('Office team hero image loaded successfully as background');
                };
                testImage.onerror = function() {
                    console.warn('Office team hero image failed to load, using fallback');
                    // Fallback to orange gradient if local image fails
                    heroSection.style.background = `
                        linear-gradient(135deg, #FFA500 0%, #FF8C00 100%)
                    `;
                };
                testImage.src = 'assets/images/hero-office-team.jpg';
            }
        });
    </script>
</body>
</html>