<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

check_role('empresa');

$user = get_logged_in_user();

// Get company
$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ?");
$stmt->execute([$user['id']]);
$company = $stmt->fetch();

if (!$company) {
    die('Company profile not found.');
}

$page_title = 'Mis Ofertas de Trabajo';

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

// Pagination and Search
$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']) : '';

// Get total count
$count_query = "SELECT COUNT(*) as total FROM jobs j LEFT JOIN careers car ON j.career_id = car.id WHERE j.company_id = ?";
$params = [$company['id']];
if ($search) {
    $count_query .= " AND (j.title LIKE ? OR j.description LIKE ? OR car.name LIKE ? OR j.location LIKE ?)";
    $params = array_merge($params, ["%$search%", "%$search%", "%$search%", "%$search%"]);
}
$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">Job deleted successfully.</div>' : '') . '
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Mis Ofertas</h3>
                <div class="card-tools">
                    <div class="total-jobs-badge">
                        <i class="fas fa-briefcase text-primary me-1"></i>
                        <span class="fw-bold text-primary">' . $total_jobs . '</span>
                        <small class="text-muted ms-1">Ofertas</small>
                    </div>
                    <a href="' . route_url('company_add_job') . '" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> Publicar Oferta</a>
                </div>
            </div>
            <div class="card-header">
                <form method="get" class="d-flex">
                    <input type="text" name="search" class="form-control" placeholder="Buscar mis ofertas de trabajo..." value="' . htmlspecialchars($search) . '">
                    <button type="submit" class="btn btn-primary ml-2"><i class="fas fa-search"></i> Buscar</button>
                    ' . ($search ? '<a href="/company/jobs" class="btn btn-secondary ml-2"><i class="fas fa-times"></i> Limpiar</a>' : '') . '
                </form>
            </div>
            <div class="card-body">
                <div class="row">';

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

$stmt = $pdo->prepare($query);
$stmt->execute($search ? array_merge([$company['id']], ["%$search%", "%$search%", "%$search%", "%$search%"]) : [$company['id']]);

while ($row = $stmt->fetch()) {

    $company_logo = $row['company_logo'] ? '<img src="../' . htmlspecialchars($row['company_logo']) . '" class="img-fluid mb-2" style="max-height: 100px;" alt="Company Logo">' : '<div class="text-center text-muted mb-2"><i class="fas fa-building fa-lg"></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>';

    $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">' . match($row['job_type']) {
                            'full-time' => 'Tiempo Completo',
                            'part-time' => 'Medio Tiempo',
                            'contract' => 'Contratado',
                            'internship' => 'Pasantia',
                            default => ucfirst($row['job_type'])
                        } . '</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'] ? date('d/m/Y', strtotime($row['expiration_date'])) : 'No especificado') . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">🔄 Estado:</span>
                            <span class="detail-value">' . match($row['status']) {
                                'active' => '<span class="badge bg-success">Activo</span>',
                                'inactive' => '<span class="badge bg-secondary">Inactivo</span>',
                                'filled' => '<span class="badge bg-info">Completado</span>',
                                default => '<span class="badge bg-dark">' . ucfirst($row['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>


                </div>
            <div class="card-footer bg-light">
                <div class="row g-1">
                    <div class="col-6">
                        <a href="' . url('company/jobs/' . $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('company_job_applications', ['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="' . url('company/jobs/' . $row['id'] . '/edit') . '" class="btn btn-warning btn-sm w-100">
                            <i class="fas fa-edit"></i> Editar
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="/company/delete-job/' . $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>';

// Pagination
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) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $content .= '<li class="page-item"><a class="page-link" href="?page=' . ($page - 1) . $search_param . '">Anterior</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Anterior</span></li>';
    }

    // Page numbers
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);

    if ($start_page > 1) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $content .= '<li class="page-item"><a class="page-link" href="?page=1' . $search_param . '">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++) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        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="?page=' . $i . $search_param . '">' . $i . '</a></li>';
        }
    }

    if ($end_page < $total_pages) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        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="?page=' . $total_pages . $search_param . '">' . $total_pages . '</a></li>';
    }

    // Next button
    if ($page < $total_pages) {
        $search_param = $search ? '&search=' . urlencode($search) : '';
        $content .= '<li class="page-item"><a class="page-link" href="?page=' . ($page + 1) . $search_param . '">Siguiente</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Siguiente</span></li>';
    }

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

$content .= '
<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;
    border: 2px solid transparent;
    background: linear-gradient(135deg, var(--cambridge-blue), var(--celadon));
    color: white;
    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-info {
    background: linear-gradient(135deg, var(--cambridge-blue), var(--celadon));
}
.card-footer .btn-success {
    background: linear-gradient(135deg, var(--celadon), var(--mint-cream));
    color: var(--caput-mortuum);
}
.card-footer .btn-warning {
    background: linear-gradient(135deg, #f39c12, #e67e22);
}
.card-footer .btn-danger {
    background: linear-gradient(135deg, #e74c3c, #c0392b);
}
.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;
}
</style>';

include __DIR__ . '/../includes/layout.php';
?>