<?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('administrador');

$user = get_logged_in_user();

// Get careers
$careers = $pdo->query("SELECT * FROM careers ORDER BY name")->fetchAll();

// Get companies
$companies = $pdo->query("SELECT c.id, c.company_name, u.username FROM companies c JOIN users u ON c.user_id = u.id ORDER BY c.company_name")->fetchAll();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $company_id = $_POST['company_id'];
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $requirements = trim($_POST['requirements']);
    $link = trim($_POST['link']);
    $salary = $_POST['salary'];
    $location = trim($_POST['location']);
    $job_type = $_POST['job_type'];
    $career_id = $_POST['career_id'];
    $expiration_date = $_POST['expiration_date'];

    if (empty($company_id) || empty($title) || empty($description)) {
        $error = 'Company, title and description are required.';
    } else {
        $stmt = $pdo->prepare("INSERT INTO jobs (company_id, career_id, title, description, requirements, link, salary, location, job_type, expiration_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$company_id, $career_id ?: null, $title, $description, $requirements, $link, $salary, $location, $job_type, $expiration_date ?: null])) {
            $success = 'Trabajo publicado exitosamente.';
        } else {
            $error = 'No se pudo publicar el trabajo.';
        }
    }
}

$page_title = 'Publicar nueva oferta de trabajo ';

$content = '
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Publicar</h3>
            </div>
            <form method="post">
                <div class="card-body">
                    ' . ($error ? '<div class="alert alert-danger">' . $error . '</div>' : '') . '
                    ' . ($success ? '<div class="alert alert-success">' . $success . '</div>' : '') . '
                    <div class="form-group">
                        <label for="company_id">Empresa</label>
                        <select class="form-control" id="company_id" name="company_id" required>
                            <option value="">Seleccionar empresa</option>';
foreach ($companies as $company) {
    $content .= '<option value="' . $company['id'] . '">' . htmlspecialchars($company['company_name']) . ' (' . htmlspecialchars($company['username']) . ')</option>';
}
$content .= '</select>
                    </div>
                    <div class="form-group">
                        <label for="title">Título del puesto</label>
                        <input type="text" class="form-control" id="title" name="title" required>
                    </div>
                    <div class="form-group">
                        <label for="description">Descripción del puesto</label>
                        <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="requirements">Requerimientos</label>
                        <textarea class="form-control" id="requirements" name="requirements" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="link">Enlace (opcional)</label>
                        <input type="url" class="form-control" id="link" name="link" placeholder="https://ejemplo.com/postulacion">
                    </div>
                    <div class="form-group">
                        <label for="career_id">Programa de Estudio</label>
                        <select class="form-control" id="career_id" name="career_id">
                            <option value="">Seleccionar Programa</option>';
foreach ($careers as $career) {
    $content .= '<option value="' . $career['id'] . '">' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '</select>
                    </div>
                    <div class="form-group">
                        <label for="salary">Sueldo</label>
                        <input type="number" class="form-control" id="salary" name="salary" step="0.01">
                    </div>
                    <div class="form-group">
                        <label for="location">Ubicación</label>
                        <input type="text" class="form-control" id="location" name="location">
                    </div>
                    <div class="form-group">
                        <label for="job_type">Tipo de Trabajo</label>
                        <select class="form-control" id="job_type" name="job_type">
                            <option value="full-time">Tiempo Completo</option>
                            <option value="part-time">Medio Tiempo</option>
                            <option value="contract">Contrato</option>
                            <option value="internship">Pasantía</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="expiration_date">Fecha de expiración</label>
                        <input type="date" class="form-control" id="expiration_date" name="expiration_date">
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Publicar oferta</button>
                    <a href="' . route_url('admin_jobs') . '" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</div>';

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