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

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

$company_id = $_SESSION['company_id'];
$company_user_id = $_SESSION['user_id'];

$message = '';

// Handle job actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $job_id = (int)$_POST['job_id'];
    $action = $_POST['action'];
    
    // Verify job belongs to this company
    $stmt = $db->prepare("SELECT id FROM jobs WHERE id = ? AND company_id = ?");
    $stmt->execute([$job_id, $company_id]);
    
    if ($stmt->fetch()) {
        try {
            if ($action === 'delete') {
                $stmt = $db->prepare("DELETE FROM jobs WHERE id = ?");
                $stmt->execute([$job_id]);
                $message = 'Job deleted successfully.';
            } elseif (in_array($action, ['activate', 'close', 'draft'])) {
                $status = '';
                switch ($action) {
                    case 'activate': $status = 'active'; break;
                    case 'close': $status = 'closed'; break;
                    case 'draft': $status = 'draft'; break;
                }
                
                $stmt = $db->prepare("UPDATE jobs SET status = ? WHERE id = ?");
                $stmt->execute([$status, $job_id]);
                $message = 'Job status updated successfully.';
            }
        } catch (PDOException $e) {
            $message = 'Error updating job: ' . $e->getMessage();
        }
    }
}

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build query conditions
$where_conditions = ["j.company_id = ?"];
$params = [$company_id];

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

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

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

// Get jobs with statistics
$stmt = $db->prepare("
    SELECT j.*, 
           jc.name as category_name,
           cu.name as posted_by,
           COUNT(ja.id) as application_count,
           COUNT(CASE WHEN ja.status = 'applied' THEN 1 END) as pending_applications,
           COUNT(CASE WHEN ja.status = 'shortlisted' THEN 1 END) as shortlisted_applications
    FROM jobs j 
    LEFT JOIN job_categories jc ON j.category_id = jc.id
    LEFT JOIN company_users cu ON j.company_user_id = cu.id
    LEFT JOIN job_applications ja ON j.id = ja.job_id
    $where_clause
    GROUP BY j.id
    ORDER BY j.created_at DESC
");
$stmt->execute($params);
$jobs = $stmt->fetchAll();

// Get summary statistics
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_jobs,
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_jobs,
        COUNT(CASE WHEN status = 'draft' THEN 1 END) as draft_jobs,
        COUNT(CASE WHEN status = 'closed' THEN 1 END) as closed_jobs
    FROM jobs 
    WHERE company_id = ?
");
$stmt->execute([$company_id]);
$stats = $stmt->fetch();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Jobs - <?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-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['company_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="post-job.php">
                                <i class="fas fa-plus-circle me-2"></i>Post New Job
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-briefcase me-2"></i>Manage Jobs
                        </h1>
                        <a href="post-job.php" class="btn btn-primary">
                            <i class="fas fa-plus me-1"></i>Post New Job
                        </a>
                    </div>

                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <i class="fas fa-briefcase fa-2x text-primary mb-2"></i>
                                    <h3 class="mb-1"><?php echo $stats['total_jobs']; ?></h3>
                                    <p class="text-muted mb-0">Total Jobs</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <i class="fas fa-eye fa-2x text-success mb-2"></i>
                                    <h3 class="mb-1"><?php echo $stats['active_jobs']; ?></h3>
                                    <p class="text-muted mb-0">Active Jobs</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <i class="fas fa-edit fa-2x text-warning mb-2"></i>
                                    <h3 class="mb-1"><?php echo $stats['draft_jobs']; ?></h3>
                                    <p class="text-muted mb-0">Draft Jobs</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <i class="fas fa-times-circle fa-2x text-secondary mb-2"></i>
                                    <h3 class="mb-1"><?php echo $stats['closed_jobs']; ?></h3>
                                    <p class="text-muted mb-0">Closed Jobs</p>
                                </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-4">
                                    <label for="search" class="form-label">Search</label>
                                    <input type="text" class="form-control" id="search" name="search" 
                                           placeholder="Job title, description, location..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                <div class="col-md-3">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">All Status</option>
                                        <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                        <option value="draft" <?php echo $status_filter === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="closed" <?php echo $status_filter === 'closed' ? 'selected' : ''; ?>>Closed</option>
                                    </select>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <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="card-title mb-0">Jobs (<?php echo count($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-4x text-muted mb-3"></i>
                                    <h3>No jobs found</h3>
                                    <p class="text-muted">You haven't posted any jobs yet or no jobs match your filters.</p>
                                    <a href="post-job.php" class="btn btn-primary">
                                        <i class="fas fa-plus me-1"></i>Post Your First Job
                                    </a>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Job Details</th>
                                                <th>Status</th>
                                                <th>Applications</th>
                                                <th>Posted</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($jobs as $job): ?>
                                                <tr>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-1"><?php echo htmlspecialchars($job['title']); ?></h6>
                                                            <small class="text-muted">
                                                                <i class="fas fa-map-marker-alt me-1"></i><?php echo htmlspecialchars($job['location']); ?>
                                                                <?php if ($job['category_name']): ?>
                                                                    • <i class="fas fa-tag me-1"></i><?php echo htmlspecialchars($job['category_name']); ?>
                                                                <?php endif; ?>
                                                                • <i class="fas fa-clock me-1"></i><?php echo ucfirst(str_replace('-', ' ', $job['employment_type'])); ?>
                                                                <?php
                                                                $job_type_badge = '';
                                                                $job_type_icon = '';
                                                                switch ($job['job_type']) {
                                                                    case 'internal':
                                                                        $job_type_badge = 'bg-warning text-dark';
                                                                        $job_type_icon = 'fas fa-user-tie';
                                                                        $job_type_text = 'Internal';
                                                                        break;
                                                                    case 'external':
                                                                        $job_type_badge = 'bg-info text-white';
                                                                        $job_type_icon = 'fas fa-globe';
                                                                        $job_type_text = 'External';
                                                                        break;
                                                                    default:
                                                                        $job_type_badge = 'bg-primary text-white';
                                                                        $job_type_icon = 'fas fa-users';
                                                                        $job_type_text = 'All';
                                                                }
                                                                ?>
                                                                • <span class="badge <?php echo $job_type_badge; ?> badge-sm">
                                                                    <i class="<?php echo $job_type_icon; ?> me-1"></i><?php echo $job_type_text; ?>
                                                                </span>
                                                                <?php
                                                                $work_location_badge = '';
                                                                $work_location_icon = '';
                                                                switch ($job['work_location_type']) {
                                                                    case 'remote':
                                                                        $work_location_badge = 'bg-success text-white';
                                                                        $work_location_icon = 'fas fa-home';
                                                                        $work_location_text = 'Remote';
                                                                        break;
                                                                    case 'hybrid':
                                                                        $work_location_badge = 'bg-warning text-dark';
                                                                        $work_location_icon = 'fas fa-arrows-alt-h';
                                                                        $work_location_text = 'Hybrid';
                                                                        break;
                                                                    default:
                                                                        $work_location_badge = 'bg-secondary text-white';
                                                                        $work_location_icon = 'fas fa-building';
                                                                        $work_location_text = 'Office';
                                                                }
                                                                ?>
                                                                • <span class="badge <?php echo $work_location_badge; ?> badge-sm">
                                                                    <i class="<?php echo $work_location_icon; ?> me-1"></i><?php echo $work_location_text; ?>
                                                                </span>
                                                            </small>
                                                            <?php if ($job['salary_min'] || $job['salary_max']): ?>
                                                                <br><small class="text-success">
                                                                    <i class="fas fa-coins me-1"></i>
                                                                    <?php 
                                                                    if ($job['salary_min'] && $job['salary_max']) {
                                                                        echo 'R' . number_format($job['salary_min']) . ' - R' . number_format($job['salary_max']);
                                                                    } elseif ($job['salary_min']) {
                                                                        echo 'From R' . number_format($job['salary_min']);
                                                                    } else {
                                                                        echo 'Up to R' . number_format($job['salary_max']);
                                                                    }
                                                                    ?>
                                                                </small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge status-<?php echo $job['status']; ?>">
                                                            <?php echo ucfirst($job['status']); ?>
                                                        </span>
                                                        <?php if ($job['deadline'] && strtotime($job['deadline']) < time()): ?>
                                                            <br><small class="text-danger">Expired</small>
                                                        <?php elseif ($job['deadline']): ?>
                                                            <br><small class="text-muted">Expires <?php echo date('M j', strtotime($job['deadline'])); ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="text-center">
                                                            <h6 class="mb-0"><?php echo $job['application_count']; ?></h6>
                                                            <small class="text-muted">Total</small>
                                                            <?php if ($job['pending_applications'] > 0): ?>
                                                                <br><span class="badge bg-warning text-dark"><?php echo $job['pending_applications']; ?> pending</span>
                                                            <?php endif; ?>
                                                            <?php if ($job['shortlisted_applications'] > 0): ?>
                                                                <br><span class="badge bg-info"><?php echo $job['shortlisted_applications']; ?> shortlisted</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <?php echo formatDate($job['created_at']); ?>
                                                            <?php if ($job['posted_by']): ?>
                                                                <br><small class="text-muted">by <?php echo htmlspecialchars($job['posted_by']); ?></small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <button type="button" class="btn btn-outline-primary dropdown-toggle" 
                                                                    data-bs-toggle="dropdown">
                                                                Actions
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a class="dropdown-item" href="../job-details.php?id=<?php echo $job['id']; ?>" target="_blank">
                                                                        <i class="fas fa-eye me-2"></i>View Public Page
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="edit-job.php?id=<?php echo $job['id']; ?>">
                                                                        <i class="fas fa-edit me-2"></i>Edit Job
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="applications.php?job_id=<?php echo $job['id']; ?>">
                                                                        <i class="fas fa-file-alt me-2"></i>View Applications (<?php echo $job['application_count']; ?>)
                                                                    </a>
                                                                </li>
                                                                <li><hr class="dropdown-divider"></li>
                                                                
                                                                <?php if ($job['status'] === 'draft'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                                            <input type="hidden" name="action" value="activate">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-play me-2"></i>Activate Job
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($job['status'] === 'active'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                                            <input type="hidden" name="action" value="close">
                                                                            <button type="submit" class="dropdown-item text-warning">
                                                                                <i class="fas fa-pause me-2"></i>Close Job
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($job['status'] === 'closed'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                                            <input type="hidden" name="action" value="activate">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-play me-2"></i>Reopen Job
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <form method="POST" class="d-inline" 
                                                                          onsubmit="return confirm('Are you sure you want to delete this job? This will also delete all applications.')">
                                                                        <input type="hidden" name="job_id" value="<?php echo $job['id']; ?>">
                                                                        <input type="hidden" name="action" value="delete">
                                                                        <button type="submit" class="dropdown-item text-danger">
                                                                            <i class="fas fa-trash me-2"></i>Delete Job
                                                                        </button>
                                                                    </form>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

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