<?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.');
}

$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$job_id) {
    header('Location: /company/jobs');
    exit;
}

// Get job details and verify ownership
$stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ? AND company_id = ?");
$stmt->execute([$job_id, $company['id']]);
$job = $stmt->fetch();

if (!$job) {
    header('Location: /company/jobs');
    exit;
}

// Get careers for dropdown
$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'];
    $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 = ?, salary = ?, location = ?, job_type = ?, career_id = ?, status = ?, expiration_date = ? WHERE id = ? AND company_id = ?");
        if ($stmt->execute([$title, $description, $requirements, $salary, $location, $job_type, $career_id, $status, $expiration_date, $job_id, $company['id']])) {
            $success = 'Trabajo actualizado exitosamente.';
            // Refresh job data
            $stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ? AND company_id = ?");
            $stmt->execute([$job_id, $company['id']]);
            $job = $stmt->fetch();
        } else {
            $error = 'No se pudo actualizar el trabajo.';
        }
    }
}

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

$content = '
<div class="row">
    <div class="col-md-8">
        <div class="card card-primary">
            <div class="card-header">
                <h3 class="card-title">Editar Trabajo</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="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="title">Cargo *</label>
                                <input type="text" class="form-control" id="title" name="title" value="' . htmlspecialchars($job['title']) . '" required>
                            </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="location">Lugar</label>
                                <input type="text" class="form-control" id="location" name="location" value="' . htmlspecialchars($job['location'] ?? '') . '">
                            </div>
                            <div class="form-group">
                                <label for="salary">Sueldo</label>
                                <input type="number" class="form-control" id="salary" name="salary" step="0.01" value="' . htmlspecialchars($job['salary'] ?? '') . '">
                            </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>
                        <div class="col-md-6">
                            <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 class="form-group">
                                <label for="description">Descripcion *</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>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Actualizar</button>
                    <a href="' . url('company/jobs.php') . '" class="btn btn-secondary">Volver</a>
                </div>
            </form>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Estadísticas</h3>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-12">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3>' . $pdo->query("SELECT COUNT(*) as total FROM applications WHERE job_id = $job_id")->fetch()['total'] . '</h3>
                                <p>Total de Postulantes</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row text-center mt-2">
                    <div class="col-6">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3>' . $pdo->query("SELECT COUNT(*) as total FROM applications WHERE job_id = $job_id AND status = 'pending'")->fetch()['total'] . '</h3>
                                <p>Pendiente</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3>' . $pdo->query("SELECT COUNT(*) as total FROM applications WHERE job_id = $job_id AND status = 'accepted'")->fetch()['total'] . '</h3>
                                <p>Acceptado</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>';

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