<?php
/**
 * @intranet-file base/enlaces/index.php
 * @intranet-file-version 2026.03.29.1
 * @intranet-file-date 2026-03-29
 * @intranet-file-owner CSIF Intranet
 */

require_once dirname(__DIR__, 2) . '/common/app_guard.php';
checkAppAccess();

require_once dirname(__DIR__, 2) . '/common/enlaces_lib.php';
require_once dirname(__DIR__, 2) . '/common/incidencias_bridge.php';

$username = (string)($_SESSION['username'] ?? '');
$givenName = (string)($_SESSION['givenName'] ?? $username);
$pageTitle = 'Peticion de enlace - Intranet';
$themeVarsPath = dirname(__DIR__, 2) . '/styles/css/theme-vars.css';
$themeVarsVersion = is_file($themeVarsPath) ? (string)filemtime($themeVarsPath) : (string)time();
$flash = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        enlaces_csrf_validate($_POST['csrf_token'] ?? null);

        $url = htmlspecialchars($_POST['url'] ?? '');
        $descripcion = htmlspecialchars($_POST['descripcion'] ?? '');
        $ambito = htmlspecialchars($_POST['ambito'] ?? '');

        if (isset($_FILES['imagen']) && $_FILES['imagen']['error'] === UPLOAD_ERR_OK) {
            $imagenTmpPath = $_FILES['imagen']['tmp_name'];

            if (!is_uploaded_file($imagenTmpPath)) {
                $flash = ['type' => 'error', 'title' => 'Error', 'message' => 'Adjunto invalido.'];
            } else {
                try {
                    $pdo = db();
                    inc_bridge_ensure_schema($pdo);

                    $categoryId = inc_bridge_get_or_create_category($pdo, 'Web/Enlaces', 70);
                    $asunto = ($ambito === 'publico') ? 'Peticion de enlace (Publico)' : 'Peticion de enlace (Privado)';

                    $deps = $_SESSION['departments'] ?? [];
                    $dept = (is_array($deps) && !empty($deps)) ? (string)$deps[0] : 'dept_general';

                    $ip = (string)($_SERVER['REMOTE_ADDR'] ?? '');
                    $ua = (string)($_SERVER['HTTP_USER_AGENT'] ?? '');
                    $ref = (string)($_SERVER['HTTP_REFERER'] ?? '');

                    $cuerpoTxt = "Peticion de enlace registrada desde la intranet.\n\n" .
                        "Usuario: {$username}\n" .
                        "Nombre: {$givenName}\n" .
                        "Departamento: {$dept}\n" .
                        "Ambito: {$ambito}\n" .
                        "URL: {$url}\n" .
                        "Descripcion:\n{$descripcion}\n\n" .
                        "IP: {$ip}\n" .
                        "Referer: {$ref}\n" .
                        "User-Agent: {$ua}\n";

                    $res = inc_bridge_create_incident($pdo, [
                        'department' => $dept,
                        'category_id' => $categoryId > 0 ? $categoryId : null,
                        'title' => $asunto,
                        'description' => $cuerpoTxt,
                        'priority' => 'media',
                        'created_by' => $username,
                    ], $_FILES['imagen']);

                    $incidentId = (int)($res['incident_id'] ?? 0);
                    $code = (string)($res['code'] ?? '');

                    if ($incidentId > 0) {
                        $urlView = '../incidencias/view.php?id=' . $incidentId;
                        $flash = [
                            'type' => 'success',
                            'title' => 'Solicitud registrada',
                            'message' => 'Se ha creado la incidencia <strong>' . h($code) . '</strong>. Puedes verla aqui: <a href="' . h($urlView) . '">abrir incidencia</a>.',
                        ];
                    } else {
                        $flash = ['type' => 'error', 'title' => 'Error', 'message' => 'No se pudo crear la incidencia.'];
                    }
                } catch (Throwable $e) {
                    error_log('Peticiones enlaces -> incidencias error: ' . $e->getMessage());
                    $flash = ['type' => 'error', 'title' => 'Error', 'message' => 'No se pudo registrar la peticion como incidencia.'];
                }
            }
        } else {
            $flash = ['type' => 'error', 'title' => 'Imagen requerida', 'message' => 'Debes adjuntar una captura de pantalla.'];
        }
    } catch (Throwable $e) {
        $flash = ['type' => 'error', 'title' => 'Sesion caducada', 'message' => 'Recarga la pagina y vuelve a intentarlo.'];
    }
}
?>
<!DOCTYPE html>
<html lang="es" class="app-html" <?= intranet_theme_html_attr(); ?>>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= h($pageTitle) ?></title>
    <?= intranet_theme_bootstrap_script_tag(); ?>
    <link rel="stylesheet" href="<?= h(asset_url('styles/css/style.css')) ?>">
    <link rel="stylesheet" href="<?= h(asset_url('styles/css/theme-vars.css')) ?>?v=<?= urlencode($themeVarsVersion) ?>">
    <style>
        .request-shell {
            max-width: 980px;
            margin: 0 auto;
        }

        .request-feedback {
            margin-bottom: 24px;
            padding: 16px 18px;
            border-radius: 12px;
            border: 1px solid transparent;
            background: var(--bg-card);
            box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
        }

        .request-feedback--success {
            background: var(--success-bg);
            border-color: var(--success-border);
            color: var(--success-text);
        }

        .request-feedback--error {
            background: var(--error-bg);
            border-color: var(--error-border);
            color: var(--error-text);
        }

        .request-feedback a {
            color: inherit;
            font-weight: 700;
        }

        .request-intro {
            display: grid;
            gap: 8px;
            margin-bottom: 24px;
        }

        .request-intro h3 {
            margin: 0;
            color: var(--primary);
        }

        .request-intro p,
        .request-help,
        .request-footer {
            color: var(--text-muted);
        }

        .request-help {
            margin-top: 8px;
            font-size: 0.92rem;
        }

        .request-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 24px;
            margin-bottom: 24px;
        }

        .request-actions {
            display: flex;
            justify-content: flex-end;
        }

        .request-submit {
            width: auto;
            padding: 15px 40px;
            font-size: 1.05rem;
        }

        .request-footer {
            margin-top: 28px;
            text-align: center;
        }

        @media (max-width: 768px) {
            .request-grid {
                grid-template-columns: 1fr;
                gap: 0;
                margin-bottom: 8px;
            }

            .request-actions {
                justify-content: stretch;
            }

            .request-submit {
                width: 100%;
            }
        }
    </style>
</head>

<body class="app-body">
    <div class="app-container request-shell">
        <header class="header-top">
            <div class="header-titles">
                <h2>Peticion de enlace</h2>
                <p>Usuario: <strong><?= h($givenName) ?></strong></p>
            </div>
            <div class="header-actions">
                <a href="<?= h(asset_url('dashboard.php')) ?>" target="_top" class="btn-back-dashboard">Volver al inicio</a>
            </div>
        </header>

        <?php if ($flash): ?>
            <div class="request-feedback request-feedback--<?= $flash['type'] === 'success' ? 'success' : 'error' ?>">
                <strong><?= h($flash['title']) ?></strong> <?= $flash['message'] ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="request-intro">
                <h3>Nueva solicitud</h3>
                <p>Si falta algun enlace util de uso comun, indicalo aqui para que podamos revisarlo y darlo de alta.</p>
                <p class="request-help">Adjunta una captura para que el equipo web tenga contexto visual al tramitar la incidencia.</p>
            </div>

            <form action="" method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?= h(enlaces_csrf_token()) ?>">
                <div class="form-group">
                    <label for="url">URL del sitio web</label>
                    <input
                        type="url"
                        id="url"
                        name="url"
                        class="form-control"
                        required
                        placeholder="https://ejemplo.com">
                </div>

                <div class="form-group">
                    <label for="descripcion">Breve descripcion</label>
                    <textarea
                        id="descripcion"
                        name="descripcion"
                        class="form-control"
                        rows="4"
                        required
                        placeholder="Explica por que es util este enlace..."></textarea>
                </div>

                <div class="request-grid">
                    <div class="form-group">
                        <label for="ambito">Ambito de visibilidad</label>
                        <select id="ambito" name="ambito" class="form-control" required>
                            <option value="publico">Publico (todos)</option>
                            <option value="privado">Privado (solo responsables)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="imagen">Imagen o captura adjunta</label>
                        <input type="file" id="imagen" name="imagen" class="form-control" accept="image/*" required>
                    </div>
                </div>

                <div class="request-actions">
                    <button type="submit" class="btn-primary request-submit">Registrar peticion</button>
                </div>
            </form>
        </div>

        <footer class="request-footer">
            &copy; <?= date('Y') ?> <?= h(function_exists('intranet_brand_name') ? intranet_brand_name() : 'Intranet') ?> | Sesion: <strong><?= h($username) ?></strong>
        </footer>
    </div>
</body>
</html>
