<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once dirname(__DIR__) . '/includes/helpers.php'; // Use relative path to bootstrap helpers

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

$user = get_logged_in_user();

$page_title = 'Ofertas de Trabajo';

$deleted = isset($_GET['deleted']) && $_GET['deleted'] == '1';

// Paginación y Búsqueda
$per_page = 12; // 12 jobs per page (4x3 grid)
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $per_page;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$career_filter = isset($_GET['career']) ? (int)$_GET['career'] : 0;

// Obtener el conteo total
$count_query = "SELECT COUNT(*) as total FROM jobs j JOIN companies c ON j.company_id = c.id LEFT JOIN careers car ON j.career_id = car.id WHERE j.deleted_at IS NULL";
$params = [];
if ($search) {
    $count_query .= " AND (j.title LIKE ? OR j.description LIKE ? OR c.company_name LIKE ? OR car.name LIKE ? OR j.location LIKE ?)";
    $params = ["%$search%", "%$search%", "%$search%", "%$search%", "%$search%"];
}
if ($career_filter > 0) {
    $count_query .= " AND j.career_id = ?";
    $params[] = $career_filter;
}
$total_stmt = $pdo->prepare($count_query);
$total_stmt->execute($params);
$total_jobs = $total_stmt->fetch()['total'];
$total_pages = ceil($total_jobs / $per_page);

$content = ($deleted ? '<div class="alert alert-success">Oferta de trabajo eliminada exitosamente.</div>' : '') . '
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Ofertas</h3>
                <div class="card-tools">
                    <div class="total-jobs-badge">
                        <i class="fas fa-briefcase text-info me-1"></i>
                        <span class="fw-bold text-info">' . $total_jobs . '</span>
                        <small class="text-muted ms-1">Ofertas</small>
                    </div>
                    <div class="btn-group">
                        <a href="' . route_url('admin_add_job') . '" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> Agregar Oferta</a>
                        <a href="' . route_url('admin_export_jobs', ['format' => 'excel', 'search' => $search, 'career' => $career_filter]) . '" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Exportar a Excel</a>
                        <a href="' . route_url('admin_export_jobs', ['format' => 'pdf', 'search' => $search, 'career' => $career_filter]) . '" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> Exportar a PDF</a>
                    </div>
                </div>
            </div>
            <div class="card-header col-12">
                <form method="get" class="row g-2 align-items-end">
                    <div class="col-md-5">
                        <label for="search" class="form-label">Buscar por texto</label>
                        <input type="text" name="search" id="search" class="form-control" placeholder="Título, empresa, descripción..." value="' . htmlspecialchars($search) . '">
                    </div>
                    <div class="col-md-5">
                        <label for="career" class="form-label">Filtrar por Programa</label>
                        <select name="career" id="career" class="form-select">
                            <option value="0">seleccione...</option>';
try {
    global $pdo;
    $careers_stmt = $pdo->query("SELECT id, name FROM careers ORDER BY name");
    $careers = $careers_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Fallback si hay error en la consulta
    $careers = [];
}
foreach ($careers as $career) {
    $selected = $career_filter == $career['id'] ? ' selected' : '';
    $content .= '<option value="' . $career['id'] . '"' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '</select>
                    </div>
                    <div class="col-md-auto">
                        <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> Buscar</button>
                    </div>
                    ' . (($search || $career_filter > 0) ? '<div class="col-md-auto">
                        <a href="' . route_url('admin_jobs') . '" class="btn btn-secondary w-100"><i class="fas fa-times"></i> Limpiar</a>
                    </div>' : '') . '
                </form>
            </div>
            <div class="card-body">
                <div class="row">';

$query = "SELECT j.*, c.company_name, c.logo as company_logo, car.name as career_name, COUNT(a.id) as app_count FROM jobs j JOIN companies c ON j.company_id = c.id LEFT JOIN careers car ON j.career_id = car.id LEFT JOIN applications a ON j.id = a.job_id WHERE j.deleted_at IS NULL";
if ($search) {
    $query .= " AND (j.title LIKE ? OR j.description LIKE ? OR c.company_name LIKE ? OR car.name LIKE ? OR j.location LIKE ?)";
}
if ($career_filter > 0) {
    $query .= " AND j.career_id = ?";
}
$query .= " GROUP BY j.id ORDER BY j.posted_date DESC LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;

$stmt = $pdo->prepare($query);
$params = [];
if ($search) {
    $params = ["%$search%", "%$search%", "%$search%", "%$search%", "%$search%"];
}
if ($career_filter > 0) {
    $params[] = $career_filter;
}
$stmt->execute($params);

while ($row = $stmt->fetch()) {
    // Verificar si la oferta ha expirado y actualizar el estado si es necesario
    $is_expired = $row['expiration_date'] && strtotime($row['expiration_date']) < time();
    $is_expiring_soon = $row['expiration_date'] && strtotime($row['expiration_date']) >= time() && strtotime($row['expiration_date']) <= strtotime('+7 days');
    $current_status = $is_expired && $row['status'] === 'active' ? 'inactive' : $row['status'];

    $status_badge = '';
    if ($current_status === 'active') {
        $status_badge = 'Activo';
    } elseif ($current_status === 'inactive') {
        $status_badge = 'Inactivo';
    } elseif ($current_status === 'filled') {
        $status_badge = 'Completado';
    } else {
        $status_badge = ucfirst($current_status);
    }

    $company_logo = $row['company_logo'] ? '<img src="' . url($row['company_logo']) . '" class="img-fluid mb-2  shadow-sm" style="max-height: 100px;" alt="Company Logo">' : '<div class="text-center text-muted mb-2"><i class="fas fa-building fa-2x"></i></div>';

    $salary_display = $row['salary'] ? '<strong>S/. ' . number_format($row['salary'], 2) . '</strong>' : '<span class="text-muted">Not specified</span>';

    $location_display = $row['location'] ? '<i class="fas fa-map-marker-alt"></i> ' . htmlspecialchars($row['location']) : '<span class="text-muted">Location not specified</span>';

    $job_type_badge = '';
    if ($row['job_type'] === 'full-time') {
        $job_type_badge = 'Tiempo Completo';
    } elseif ($row['job_type'] === 'part-time') {
        $job_type_badge = 'Medio Tiempo';
    } elseif ($row['job_type'] === 'contract') {
        $job_type_badge = 'Contratado';
    } elseif ($row['job_type'] === 'internship') {
        $job_type_badge = 'Pasantia';
    } else {
        $job_type_badge = ucfirst($row['job_type']);
    }

$content .= '<div class="col-md-6 col-lg-3 mb-4">
        <div class="card h-100 job-card-modern shadow-sm">
            <div class="card-header text-center bg-gradient-cambridge">
                <div class="company-logo-container">
                    ' . $company_logo . '
                </div>
                <div class="company-logo-container mb-1 text-white font-weight-bold">
                    ' . htmlspecialchars($row['title']) . '
                </div>
                
                <div class="mt-2">
                    <span class="badge bg-celadon text-black-bean">' . $job_type_badge . '</span>
                </div>
            </div>
            <div class="card-body">
                <div class="job-details">
                    <div class="detail-row">
                        <span class="detail-label">📚 Programa:</span>
                        <span class="detail-value">' . htmlspecialchars($row['career_name'] ?: 'General') . '</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">📍 Lugar:</span>
                        <span class="detail-value">' . $location_display . '</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">💰 Sueldo:</span>
                        <span class="detail-value">' . $salary_display . '</span>
                    </div>
                    
                    <div class="detail-row">
                        <span class="detail-label">⏰ Cierre:</span>
                        <span class="detail-value">' . ($row['expiration_date'] ? '<span class="' . (strtotime($row['expiration_date']) < time() ? 'text-danger fw-bold' : (strtotime($row['expiration_date']) >= time() && strtotime($row['expiration_date']) <= strtotime('+7 days') ? 'text-warning fw-bold' : '')) . '">' . date('d/m/Y', strtotime($row['expiration_date'])) . '</span>' . ($is_expiring_soon ? ' <i class="fas fa-exclamation-triangle text-warning" title="Expira pronto"></i>' : '') : 'No especificado') . '</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">🔄 Estado:</span>
                        <span class="detail-value">' . match($current_status) {
                            'active' => '<span class="badge bg-success">Activo</span>' . ($is_expiring_soon ? ' <button class="btn btn-sm btn-outline-warning ms-1" onclick="changeJobStatus(' . $row['id'] . ', \'inactive\')" title="Marcar como inactivo"><i class="fas fa-pause"></i></button>' : ''),
                            'inactive' => '<span class="badge bg-danger">Inactivo</span>' . ($is_expiring_soon ? ' <button class="btn btn-sm btn-outline-success ms-1" onclick="changeJobStatus(' . $row['id'] . ', \'active\')" title="Reactivar oferta"><i class="fas fa-play"></i></button>' : ''),
                            'filled' => '<span class="badge bg-secondary">Completado</span>',
                            default => '<span class="badge bg-dark">' . ucfirst($current_status) . '</span>'
                        } . '</span>
                    </div>
                    ' . ($row['link'] ? '<div class="detail-row">
                        <span class="detail-label">🔗 Enlace:</span>
                        <span class="detail-value"><a href="' . htmlspecialchars($row['link']) . '" target="_blank" rel="noopener noreferrer" class="text-decoration-none"><i class="fas fa-external-link-alt"></i> Ver enlace</a></span>
                    </div>' : '') . '
                </div>

                <!-- Auto-actualizar ofertas expiradas a inactivas -->
                ' . ($is_expired && $row['status'] === 'active' ? '<script>
                    fetch("' . route_url('admin_auto_update_job_status') . '", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ job_id: \'' . $row['id'] . '\', status: "inactive" })
                    });
                </script>' : '') . '';


    $content .= '</div>
            <div class="card-footer bg-light">
                <div class="row g-1">
                    <div class="col-6">
                        <a href="' . route_url('admin_job_view', ['id' => $row['id']]) . '" class="btn btn-info btn-sm w-100 mb-1">
                            <i class="fas fa-eye"></i> Ver
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="' . route_url('admin_job_applications_id', ['id' => $row['id']]) . '" class="btn btn-success btn-sm w-100 mb-1">
                            <i class="fas fa-users"></i> Postulantes (' . $row['app_count'] . ')
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="' . route_url('admin_edit_job', ['id' => $row['id']]) . '" class="btn btn-warning btn-sm w-100">
                            <i class="fas fa-edit"></i> Editar
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="' . route_url('admin_delete_job', ['id' => $row['id']]) . '" class="btn btn-danger btn-sm w-100" onclick="return confirm(\'¿Estás seguro de que deseas eliminar esta oferta de trabajo?\')">
                            <i class="fas fa-trash"></i> Eliminar
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>';
}

$content .= '</div>
            </div>
        </div>
    </div>
</div>';

// Paginación
if ($total_pages > 1) {
    $content .= '<div class="row">
        <div class="col-12">
            <nav aria-label="Job pagination">
                <ul class="pagination justify-content-center">';

    // Previous button
    if ($page > 1) { // Botón anterior
        $params = array_filter(['page' => $page - 1, 'search' => $search, 'career' => $career_filter]);
        $content .= '<li class="page-item"><a class="page-link" href="' . route_url('admin_jobs', $params) . '">Anterior</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Anterior</span></li>';
    }

    // Números de página
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);

    if ($start_page > 1) {
        $params = array_filter(['page' => 1, 'search' => $search, 'career' => $career_filter]);
        $content .= '<li class="page-item"><a class="page-link" href="' . route_url('admin_jobs', $params) . '">1</a></li>';
        if ($start_page > 2) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }

    for ($i = $start_page; $i <= $end_page; $i++) {
        $params = array_filter(['page' => $i, 'search' => $search, 'career' => $career_filter]);
        if ($i == $page) {
            $content .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $content .= '<li class="page-item"><a class="page-link" href="' . route_url('admin_jobs', $params) . '">' . $i . '</a></li>';
        }
    }

    if ($end_page < $total_pages) {
        $params = array_filter(['page' => $total_pages, 'search' => $search, 'career' => $career_filter]);
        if ($end_page < $total_pages - 1) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
        $content .= '<li class="page-item"><a class="page-link" href="' . route_url('admin_jobs', $params) . '">' . $total_pages . '</a></li>';
    }

    // Botón siguiente
    if ($page < $total_pages) {
        $params = array_filter(['page' => $page + 1, 'search' => $search, 'career' => $career_filter]);
        $content .= '<li class="page-item"><a class="page-link" href="' . route_url('admin_jobs', $params) . '">Siguiente</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Siguiente</span></li>';
    }

    $content .= '</ul>
            </nav>
        </div>
    </div>';
}

$content .= '
<script>
function changeJobStatus(jobId, newStatus) {
    if (confirm("¿Estás seguro de que deseas cambiar el estado de esta oferta?")) {
        fetch("' . route_url('admin_auto_update_job_status') . '", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ job_id: jobId, status: newStatus })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert("Error al actualizar el estado");
            }
        })
        .catch(error => {
            console.error("Error:", error);
            alert("Error al actualizar el estado");
        });
    }
}
</script>
<style>
.job-card-modern {
    border: 2px solid var(--celadon);
    border-radius: 20px;
    overflow: hidden;
    background: linear-gradient(145deg, #ffffff, var(--mint-cream));
    box-shadow: 0 6px 20px rgba(121, 183, 145, 0.15);
    position: relative;
}
.job-card-modern::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--cambridge-blue), var(--celadon));
}
.job-card-modern .card-header {
    background: #9BABBF !important;
    border: none;
    padding: 2rem 1.5rem 1.5rem;
    position: relative;
}
.job-card-modern .card-header::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60%;
    height: 3px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
}
.job-card-modern .card-body {
    padding: 2rem 1.5rem;
    background: linear-gradient(180deg, rgba(237, 244, 237, 0.3), rgba(255, 255, 255, 0.8));
}
.job-card-modern .card-footer {
    border: none;
    padding: 1.5rem;
    background: var(--mint-cream);
    border-top: 2px solid var(--celadon);
}
.company-logo-container {
    margin-bottom: 1rem;
}
.detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.75rem;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--celadon);
    background: rgba(237, 244, 237, 0.3);
    border-radius: 8px;
    padding-left: 0.75rem;
    padding-right: 0.75rem;
    margin-left: -0.75rem;
    margin-right: -0.75rem;
}
.detail-row:last-child {
    border-bottom: none;
    margin-bottom: 0;
}
.detail-label {
    font-weight: 600;
    color: var(--caput-mortuum);
    font-size: 0.875rem;
    display: flex;
    align-items: center;
}
.detail-value {
    color: var(--black-bean);
    font-weight: 500;
    text-align: right;
    flex: 1;
    margin-left: 1rem;
}
.card-footer .btn {
    border-radius: 8px !important;
    font-weight: 500;
    padding: 0.5rem 0.25rem;
    transition: all 0.3s ease;
    border: 2px solid transparent;
    background: linear-gradient(135deg, var(--cambridge-blue), var(--celadon));
    color: white;
    position: relative;
    overflow: hidden;
    font-size: 0.8rem;
    line-height: 1.2;
    min-height: 2.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.card-footer .btn::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}

.card-footer .btn:hover::before {
    left: 100%;
}

.card-footer .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(121, 183, 145, 0.3);
    border-color: var(--celadon);
}

.card-footer .btn-info {
    background: #17a2b8;
    color: white;
}

.card-footer .btn-success {
    background: #28a745;
    color: white;
}

.card-footer .btn-warning {
    background: #ffc107;
    color: #212529;
}

.card-footer .btn-danger {
    background: #dc3545;
    color: white;
}
.badge {
    font-size: 0.75rem;
    padding: 0.5rem 0.75rem;
    border-radius: 20px;
    font-weight: 500;
    border: 1px solid rgba(255,255,255,0.3);
}
@media (max-width: 768px) {
    .detail-row {
        flex-direction: column;
        align-items: flex-start;
    }
    .detail-value {
        margin-left: 0;
        margin-top: 0.25rem;
        text-align: left;
    }
    .job-card-modern .card-header,
    .job-card-modern .card-body,
    .job-card-modern .card-footer {
        padding: 1rem;
    }
}
/* Text color improvements */
.text-white-80 {
    color: rgba(255, 255, 255, 0.8) !important;
}

/* Total Jobs Badge Styling */
.total-jobs-badge {
    display: inline-flex;
    align-items: center;
    background: linear-gradient(135deg, #e3f2fd, #f3e5f5);
    border: 2px solid #2196f3;
    border-radius: 25px;
    padding: 0.5rem 1rem;
    margin-right: 0.5rem;
    box-shadow: 0 2px 8px rgba(33, 150, 243, 0.15);
    transition: all 0.3s ease;
    font-size: 0.875rem;
}

.total-jobs-badge:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(33, 150, 243, 0.25);
    border-color: #1976d2;
}

.total-jobs-badge i {
    font-size: 1rem;
}

.total-jobs-badge .fw-bold {
    font-size: 1.1rem;
    margin: 0 0.25rem;
}

.total-jobs-badge small {
    font-weight: 500;
}

/* Top buttons styling */
.card-tools .btn-group {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
}

.card-tools .btn-group .btn {
    border-radius: 0 !important;
    border: none !important;
    font-weight: 500;
    padding: 0.5rem 1rem;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.card-tools .btn-group .btn::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}

.card-tools .btn-group .btn:hover::before {
    left: 100%;
}

.card-tools .btn-group .btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-tools .btn-group .btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>';


include BASE_PATH . '/includes/layout.php';