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

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

$job_id = $_GET['id'] ?? 0;
if (!$job_id) {
    header('Location: jobs.php');
    exit;
}

// Get job data
$stmt = $pdo->prepare("SELECT j.*, c.company_name FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.id = ?");
$stmt->execute([$job_id]);
$job = $stmt->fetch();

if (!$job) {
    header('Location: jobs.php');
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $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'];
    $status = $_POST['status'];
    $expiration_date = $_POST['expiration_date'];

    if (empty($title) || empty($description)) {
        $error = 'Se requieren título y descripción.';
    } else {
        $stmt = $pdo->prepare("UPDATE jobs SET title = ?, description = ?, requirements = ?, link = ?, salary = ?, location = ?, job_type = ?, career_id = ?, status = ?, expiration_date = ? WHERE id = ?");
        if ($stmt->execute([$title, $description, $requirements, $link, $salary, $location, $job_type, $career_id ?: null, $status, $expiration_date ?: null, $job_id])) {
            $success = 'Trabajo actualizado exitosamente.';
            // Refresh job data
            $stmt = $pdo->prepare("SELECT j.*, c.company_name FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.id = ?");
            $stmt->execute([$job_id]);
            $job = $stmt->fetch();
        } else {
            $error = 'No se pudo actualizar el trabajo.';
        }
    }
}

$page_title = 'Editar oferta de trabajo - ' . htmlspecialchars($job['title']);

$cancel_url = route_url('admin_jobs');

$content = '
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar</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">Título del puesto</label>
                        <input type="text" class="form-control" id="title" name="title" value="' . htmlspecialchars($job['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>' . htmlspecialchars($job['description']) . '</textarea>
                    </div>
                    <div class="form-group">
                        <label for="requirements">Requerimientos</label>
                        <textarea class="form-control" id="requirements" name="requirements" rows="3">' . htmlspecialchars($job['requirements'] ?: '') . '</textarea>
                    </div>
                    <div class="form-group">
                        <label for="link">Enlace (opcional)</label>
                        <input type="url" class="form-control" id="link" name="link" value="' . htmlspecialchars($job['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) {
    $selected = $job['career_id'] == $career['id'] ? 'selected' : '';
    $content .= '<option value="' . $career['id'] . '" ' . $selected . '>' . 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" value="' . htmlspecialchars($job['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" value="' . htmlspecialchars($job['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" ' . ($job['job_type'] == 'full-time' ? 'selected' : '') . '>Tiempo Completo</option>
                            <option value="part-time" ' . ($job['job_type'] == 'part-time' ? 'selected' : '') . '>Medio Tiempo</option>
                            <option value="contract" ' . ($job['job_type'] == 'contract' ? 'selected' : '') . '>Contrato</option>
                            <option value="internship" ' . ($job['job_type'] == 'internship' ? 'selected' : '') . '>Pasantía</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="status">Estado</label>
                        <select class="form-control" id="status" name="status">
                            <option value="active" ' . ($job['status'] == 'active' ? 'selected' : '') . '>Activo</option>
                            <option value="inactive" ' . ($job['status'] == 'inactive' ? 'selected' : '') . '>Inactivo</option>
                            <option value="filled" ' . ($job['status'] == 'filled' ? 'selected' : '') . '>Completado</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" value="' . htmlspecialchars($job['expiration_date'] ?: '') . '">
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar</button>
                    <a href="' . url('admin/jobs') . '" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Volver</a>
                </div>
            </form>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Información del puesto de trabajo</h3>
            </div>
            <div class="card-body">
                <p><strong>Empresa:</strong> ' . htmlspecialchars($job['company_name']) . '</p>
                <p><strong>Fecha de publicación:</strong> ' . date('d/m/Y', strtotime($job['posted_date'])) . '</p>
                <p><strong>Postulantes:</strong> ';
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM applications WHERE job_id = ?");
$stmt->execute([$job_id]);
$content .= $stmt->fetch()['count'] . '</p>
            </div>
        </div>
    </div>
</div>';

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