<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../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.');
}

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

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

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

    if (empty($title) || empty($description)) {
        $error = 'Se requieren título y descripción.';
    } else {
        $stmt = $pdo->prepare("INSERT INTO jobs (company_id, career_id, title, description, requirements, salary, location, job_type, expiration_date, link) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$company['id'], $career_id ?: null, $title, $description, $requirements, $salary, $location, $job_type, $expiration_date ?: null, $link ?: null])) {
            $job_id = $pdo->lastInsertId();
            $success = 'Trabajo publicado con éxito.';

            // Send notifications to students with matching career
            if ($career_id) {
                // Get all students with matching career
                $student_stmt = $pdo->prepare("SELECT u.id as user_id, u.first_name, u.last_name FROM users u JOIN students s ON u.id = s.user_id WHERE s.career_id = ? AND u.role_id = (SELECT id FROM roles WHERE name = 'alumno')");
                $student_stmt->execute([$career_id]);
                $matching_students = $student_stmt->fetchAll();

                // Send notification to each matching student
                $notification_stmt = $pdo->prepare("INSERT INTO notifications (user_id, type, title, message) VALUES (?, 'info', ?, ?)");
                foreach ($matching_students as $student) {
                    $student_name = htmlspecialchars($student['first_name'] . ' ' . $student['last_name']);
                    $job_title = htmlspecialchars($title);
                    $company_name = htmlspecialchars($company['company_name']);

                    $notification_stmt->execute([
                        $student['user_id'],
                        'Nueva Oferta de Trabajo',
                        "¡Hola {$student_name}! Se ha publicado una nueva oferta de trabajo que coincide con tu carrera: '{$job_title}' en {$company_name}. ¡Revisa las oportunidades disponibles!"
                    ]);
                }
            }
        } 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="title">Titulo del Trabajo</label>
                        <input type="text" class="form-control" id="title" name="title" required>
                    </div>
                    <div class="form-group">
                        <label for="description">Descripcion</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="salary">Sueldo</label>
                        <input type="number" class="form-control" id="salary" name="salary" step="0.01">
                    </div>
                    <div class="form-group">
                        <label for="location">Lugar</label>
                        <input type="text" class="form-control" id="location" name="location">
                    </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 (Opcional)</option>';
foreach ($careers as $career) {
    $content .= '<option value="' . $career['id'] . '">' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '</select>
                    </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 Expiracion</label>
                        <input type="date" class="form-control" id="expiration_date" name="expiration_date">
                    </div>
                    <div class="form-group">
                        <label for="link">Enlace Externo (Opcional)</label>
                        <input type="url" class="form-control" id="link" name="link" placeholder="https://ejemplo.com/oferta-trabajo">
                        <small class="form-text text-muted">Enlace a la oferta de trabajo en tu sitio web o plataforma externa</small>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Publicar</button>
                    <a href="' . route_url('company_jobs') . '" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</div>';

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