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

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

// Handle search and filters
$search = $_GET['search'] ?? '';
$company_filter = $_GET['company'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$employment_type_filter = $_GET['employment_type'] ?? '';

// Build query with filters
$where_conditions = ["1=1"];
$params = [];

if ($search) {
    $where_conditions[] = "(j.title LIKE ? OR j.description LIKE ? OR j.requirements LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($company_filter) {
    $where_conditions[] = "c.id = ?";
    $params[] = $company_filter;
}

if ($category_filter) {
    $where_conditions[] = "j.category_id = ?";
    $params[] = $category_filter;
}

if ($status_filter) {
    $where_conditions[] = "j.status = ?";
    $params[] = $status_filter;
}

if ($employment_type_filter) {
    $where_conditions[] = "j.employment_type = ?";
    $params[] = $employment_type_filter;
}

$where_clause = implode(' AND ', $where_conditions);

// Get jobs with pagination
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

$stmt = $db->prepare("
    SELECT j.*, c.name as company_name, c.logo,
           cat.name as category_name,
           COUNT(ja.id) as application_count,
           DATE(j.created_at) as posted_date,
           DATEDIFF(j.deadline, NOW()) as days_until_deadline
    FROM jobs j
    JOIN companies c ON j.company_id = c.id
    LEFT JOIN job_categories cat ON j.category_id = cat.id
    LEFT JOIN job_applications ja ON j.id = ja.job_id
    WHERE $where_clause
    GROUP BY j.id
    ORDER BY j.created_at DESC
    LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$jobs = $stmt->fetchAll();

// Get total count for pagination
$count_stmt = $db->prepare("
    SELECT COUNT(DISTINCT j.id) 
    FROM jobs j
    JOIN companies c ON j.company_id = c.id
    LEFT JOIN job_categories cat ON j.category_id = cat.id
    WHERE $where_clause
");
$count_stmt->execute($params);
$total_jobs = $count_stmt->fetchColumn();
$total_pages = ceil($total_jobs / $limit);

// Get job statistics
$stats_stmt = $db->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed,
        SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END) as draft,
        COUNT(CASE WHEN deadline >= CURDATE() THEN 1 END) as open_for_applications
    FROM jobs
");
$stats = $stats_stmt->fetch();

// Get applications statistics
$app_stats_stmt = $db->query("
    SELECT 
        COUNT(*) as total_applications,
        COUNT(DISTINCT job_id) as jobs_with_applications
    FROM job_applications
");
$app_stats = $app_stats_stmt->fetch();

// Get companies for filter dropdown
$companies_stmt = $db->query("SELECT id, name FROM companies ORDER BY name");
$companies = $companies_stmt->fetchAll();

// Get categories for filter dropdown
$categories_stmt = $db->query("SELECT id, name FROM job_categories ORDER BY name");
$categories = $categories_stmt->fetchAll();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $job_id = (int)$_POST['job_id'];
    
    if ($_POST['action'] === 'toggle_status') {
        $new_status = $_POST['new_status'];
        $stmt = $db->prepare("UPDATE jobs SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $job_id]);
        header("Location: jobs.php?" . http_build_query($_GET));
        exit;
    }
}

// Get status color class
function getStatusClass($status) {
    switch($status) {
        case 'active': return 'success';
        case 'closed': return 'secondary';
        case 'draft': return 'warning';
        default: return 'secondary';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jobs Management - Admin Panel</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>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i>RecruitPro Admin
            </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="dashboard.php">
                            <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="companies.php">
                            <i class="fas fa-building me-1"></i>Companies
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="candidates.php">
                            <i class="fas fa-users me-1"></i>Candidates
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="jobs.php">
                            <i class="fas fa-briefcase me-1"></i>Jobs
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="categories.php">
                            <i class="fas fa-tags me-1"></i>Categories
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="applications.php">
                            <i class="fas fa-file-alt me-1"></i>Applications
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i>Admin
                        </a>
                        <ul class="dropdown-menu">
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../auth/logout.php">Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-briefcase me-2"></i>Jobs Management</h1>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $stats['total']; ?></h4>
                                        <p class="mb-0">Total Jobs</p>
                                    </div>
                                    <i class="fas fa-briefcase fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $stats['active']; ?></h4>
                                        <p class="mb-0">Active Jobs</p>
                                    </div>
                                    <i class="fas fa-check-circle fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $stats['open_for_applications']; ?></h4>
                                        <p class="mb-0">Open for Applications</p>
                                    </div>
                                    <i class="fas fa-calendar-check fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $app_stats['total_applications']; ?></h4>
                                        <p class="mb-0">Total Applications</p>
                                    </div>
                                    <i class="fas fa-file-alt fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Search Jobs</label>
                                <input type="text" class="form-control" name="search" 
                                       value="<?php echo htmlspecialchars($search); ?>" 
                                       placeholder="Job title, description...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Company</label>
                                <select class="form-select" name="company">
                                    <option value="">All Companies</option>
                                    <?php foreach ($companies as $company): ?>
                                        <option value="<?php echo $company['id']; ?>" 
                                                <?php echo $company_filter == $company['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($company['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Category</label>
                                <select class="form-select" name="category">
                                    <option value="">All Categories</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>" 
                                                <?php echo $category_filter == $category['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($category['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Statuses</option>
                                    <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="closed" <?php echo $status_filter === 'closed' ? 'selected' : ''; ?>>Closed</option>
                                    <option value="draft" <?php echo $status_filter === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="fas fa-search me-1"></i>Filter
                                </button>
                                <a href="jobs.php" class="btn btn-outline-secondary">Clear</a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Jobs List -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Jobs (<?php echo $total_jobs; ?>)</h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($jobs)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-briefcase fa-3x text-muted mb-3"></i>
                                <h5>No jobs found</h5>
                                <p class="text-muted">
                                    <?php if ($status_filter || $search || $company_filter || $category_filter): ?>
                                        Try adjusting your filters or <a href="jobs.php">view all jobs</a>.
                                    <?php else: ?>
                                        No jobs have been posted yet.
                                    <?php endif; ?>
                                </p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead>
                                        <tr>
                                            <th>Job Details</th>
                                            <th>Company</th>
                                            <th>Category</th>
                                            <th>Applications</th>
                                            <th>Deadline</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($jobs as $job): ?>
                                            <tr>
                                                <td>
                                                    <div>
                                                        <strong><?php echo htmlspecialchars($job['title']); ?></strong>
                                                        <br>
                                                        <small class="text-muted">
                                                            <i class="fas fa-map-marker-alt me-1"></i>
                                                            <?php echo htmlspecialchars($job['location']); ?>
                                                        </small>
                                                        <br>
                                                        <small class="text-success">
                                                            <i class="fas fa-dollar-sign me-1"></i>
                                                            $<?php echo number_format($job['salary_min']); ?> - $<?php echo number_format($job['salary_max']); ?>
                                                        </small>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <?php if ($job['logo']): ?>
                                                            <img src="../uploads/logos/<?php echo htmlspecialchars($job['logo']); ?>" 
                                                                 alt="Logo" class="me-2" width="32" height="32" style="object-fit: cover;">
                                                        <?php else: ?>
                                                            <div class="bg-secondary rounded me-2 d-flex align-items-center justify-content-center" 
                                                                 style="width: 32px; height: 32px;">
                                                                <i class="fas fa-building text-white"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <span><?php echo htmlspecialchars($job['company_name']); ?></span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <?php if ($job['category_name']): ?>
                                                        <span class="badge bg-info">
                                                            <?php echo htmlspecialchars($job['category_name']); ?>
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="text-muted">Uncategorized</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <strong><?php echo $job['application_count']; ?></strong> applications
                                                    <?php if ($job['application_count'] > 0): ?>
                                                        <br>
                                                        <a href="applications.php?job_id=<?php echo $job['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                            View Applications
                                                        </a>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($job['deadline']): ?>
                                                        <small class="text-muted">
                                                            <?php echo date('M j, Y', strtotime($job['deadline'])); ?>
                                                        </small>
                                                        <?php if ($job['days_until_deadline'] !== null): ?>
                                                            <br>
                                                            <?php if ($job['days_until_deadline'] > 0): ?>
                                                                <small class="text-success"><?php echo $job['days_until_deadline']; ?> days left</small>
                                                            <?php elseif ($job['days_until_deadline'] == 0): ?>
                                                                <small class="text-warning">Expires today</small>
                                                            <?php else: ?>
                                                                <small class="text-danger">Expired</small>
                                                            <?php endif; ?>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <span class="text-muted">No deadline</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-<?php echo getStatusClass($job['status']); ?>">
                                                        <?php echo ucfirst($job['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="../job-details.php?id=<?php echo $job['id']; ?>" 
                                                           class="btn btn-outline-primary" title="View Job">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        
                                                        <!-- Status Toggle -->
                                                        <div class="dropdown">
                                                            <button class="btn btn-outline-secondary dropdown-toggle" type="button" 
                                                                    data-bs-toggle="dropdown" title="Change Status">
                                                                <i class="fas fa-cog"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <?php if ($job['status'] !== 'active'): ?>
                                                                    <li>
                                                                        <form method="POST" class="dropdown-item-form">
                                                                            <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                                            <input type="hidden" name="action" value="toggle_status">
                                                                            <input type="hidden" name="new_status" value="active">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-play me-1"></i>Activate Job
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                <?php if ($job['status'] !== 'closed'): ?>
                                                                    <li>
                                                                        <form method="POST" class="dropdown-item-form">
                                                                            <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                                            <input type="hidden" name="action" value="toggle_status">
                                                                            <input type="hidden" name="new_status" value="closed">
                                                                            <button type="submit" class="dropdown-item text-secondary">
                                                                                <i class="fas fa-times me-1"></i>Close Job
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                                <div class="card-footer">
                                    <nav aria-label="Jobs pagination">
                                        <ul class="pagination justify-content-center mb-0">
                                            <?php if ($page > 1): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&company=<?php echo urlencode($company_filter); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>">
                                                        Previous
                                                    </a>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php for ($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&company=<?php echo urlencode($company_filter); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>">
                                                        <?php echo $i; ?>
                                                    </a>
                                                </li>
                                            <?php endfor; ?>
                                            
                                            <?php if ($page < $total_pages): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&company=<?php echo urlencode($company_filter); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>">
                                                        Next
                                                    </a>
                                                </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .dropdown-item-form {
            margin: 0;
            padding: 0;
        }
        .dropdown-item-form button {
            border: none;
            background: none;
            width: 100%;
            text-align: left;
        }
    </style>
</body>
</html>