<?php
declare(strict_types=1);


include __DIR__ . '/sesion.php';
include __DIR__ . '/concha.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: text/html; charset=utf-8');

if (!isset($conn) || !($conn instanceof mysqli)) {
    die('Error: no existe la conexión mysqli en $conn.');
}

$ID = isset($_GET['ID']) ? (int)$_GET['ID'] : 0;
if ($ID <= 0) {
    die('Error: ID inválido.');
}

/* =========================================================
   RUTAS
   ========================================================= */
$siteRoot = dirname(__DIR__);
$anio = date('Y');
$mes = date('m');
$carpeta = $mes . '-' . $anio;
$uploadDir = $siteRoot . DIRECTORY_SEPARATOR . $carpeta;
$uploadUrlRel = '../' . $carpeta;

$status = '';
$statusClass = '';
$debug = [];

if (!is_dir($uploadDir)) {
    if (!@mkdir($uploadDir, 0777, true) && !is_dir($uploadDir)) {
        die('Error: no se pudo crear la carpeta de subida: ' . htmlspecialchars($uploadDir));
    }
}

if (!is_writable($uploadDir)) {
    @chmod($uploadDir, 0777);
}

/* =========================================================
   HELPERS
   ========================================================= */
function h(string $v): string
{
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

function extFromMime(string $mime): ?string
{
    return match ($mime) {
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/gif'  => 'gif',
        'image/webp' => 'webp',
        default      => null,
    };
}

function createImageResource(string $file, string $mime)
{
    return match ($mime) {
        'image/jpeg' => @imagecreatefromjpeg($file),
        'image/png'  => @imagecreatefrompng($file),
        'image/gif'  => @imagecreatefromgif($file),
        'image/webp' => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($file) : false,
        default      => false,
    };
}

function saveImageResource($img, string $dest, string $ext): bool
{
    return match ($ext) {
        'jpg', 'jpeg' => @imagejpeg($img, $dest, 85),
        'png'         => @imagepng($img, $dest, 6),
        'gif'         => @imagegif($img, $dest),
        'webp'        => function_exists('imagewebp') ? @imagewebp($img, $dest, 85) : false,
        default       => false,
    };
}

function preserveTransparency($dst, string $ext): void
{
    if (in_array($ext, ['png', 'gif', 'webp'], true)) {
        @imagealphablending($dst, false);
        @imagesavealpha($dst, true);
        $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
        @imagefill($dst, 0, 0, $transparent);
    }
}

/*
|--------------------------------------------------------------------------
| Redimensionar sin recortar
|--------------------------------------------------------------------------
| - Mantiene proporción
| - No agranda si la imagen ya es más chica
| - Limita por ancho máximo
*/
function makeResizeNoCrop(string $srcFile, string $destFile, string $mime, string $ext, int $maxWidth): bool
{
    if (!function_exists('imagecreatetruecolor')) {
        return @copy($srcFile, $destFile);
    }

    $src = createImageResource($srcFile, $mime);
    if (!$src) {
        return @copy($srcFile, $destFile);
    }

    $w = imagesx($src);
    $h = imagesy($src);

    if ($w <= 0 || $h <= 0) {
        imagedestroy($src);
        return false;
    }

    // Si ya es más chica, se deja igual
    if ($w <= $maxWidth) {
        imagedestroy($src);
        return @copy($srcFile, $destFile);
    }

    $newW = $maxWidth;
    $newH = (int) round(($h * $newW) / $w);

    $dst = imagecreatetruecolor($newW, $newH);
    preserveTransparency($dst, $ext);

    $ok = @imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
    if (!$ok) {
        imagedestroy($src);
        imagedestroy($dst);
        return false;
    }

    $saved = saveImageResource($dst, $destFile, $ext);

    imagedestroy($src);
    imagedestroy($dst);

    return $saved;
}

function cargarNota(mysqli $conn, int $id): array
{
    $sql = "SELECT foto, ext_img, carpetafoto FROM notas WHERE ID = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return ['foto' => '', 'ext_img' => '', 'carpetafoto' => ''];
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    if (!$row) {
        return ['foto' => '', 'ext_img' => '', 'carpetafoto' => ''];
    }

    return [
        'foto' => (string)($row['foto'] ?? ''),
        'ext_img' => (string)($row['ext_img'] ?? ''),
        'carpetafoto' => (string)($row['carpetafoto'] ?? '')
    ];
}

/* =========================================================
   SUBIDA
   ========================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'upload') {

    if (!isset($_FILES['archivo'])) {
        $status = 'No llegó el archivo.';
        $statusClass = 'error';
    } else {
        $file = $_FILES['archivo'];

        $debug[] = 'tmp_name: ' . ($file['tmp_name'] ?? '');
        $debug[] = 'name: ' . ($file['name'] ?? '');
        $debug[] = 'size: ' . (string)($file['size'] ?? 0);
        $debug[] = 'error: ' . (string)($file['error'] ?? -1);
        $debug[] = 'uploadDir: ' . $uploadDir;

        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            $status = 'Error de upload PHP. Código: ' . (int)$file['error'];
            $statusClass = 'error';
        } elseif (!is_uploaded_file($file['tmp_name'])) {
            $status = 'PHP no reconoce el archivo como subida válida.';
            $statusClass = 'error';
        } else {
            $tmp = $file['tmp_name'];
            $size = (int)$file['size'];

            if ($size <= 0) {
                $status = 'El archivo está vacío.';
                $statusClass = 'error';
            } elseif ($size > 5 * 1024 * 1024) {
                $status = 'La imagen supera 5 MB.';
                $statusClass = 'error';
            } else {
                $imgInfo = @getimagesize($tmp);
                $mime = $imgInfo['mime'] ?? '';

                $ext = extFromMime($mime);

                if (!$ext) {
                    $status = 'Formato no permitido. Solo JPG, PNG, GIF o WEBP.';
                    $statusClass = 'error';
                } else {
                    $timeUnix = time();

                    $resizeName = 'resize_' . $timeUnix . '.' . $ext;
                    $thumbName  = 'thumbnail_' . $timeUnix . '.' . $ext;

                    $resizePath = $uploadDir . DIRECTORY_SEPARATOR . $resizeName;
                    $thumbPath  = $uploadDir . DIRECTORY_SEPARATOR . $thumbName;
                    $tempPath   = $uploadDir . DIRECTORY_SEPARATOR . 'original_' . $timeUnix . '.' . $ext;

                    if (!@move_uploaded_file($tmp, $tempPath)) {
                        $status = 'No se pudo mover el archivo al servidor.';
                        $statusClass = 'error';
                    } else {
                        // SIN RECORTE:
                        // thumbnail = ancho máximo 600
                        // resize    = ancho máximo 1600
                        $okThumb  = makeResizeNoCrop($tempPath, $thumbPath, $mime, $ext, 600);
                        $okResize = makeResizeNoCrop($tempPath, $resizePath, $mime, $ext, 1600);

                        if (!$okThumb) {
                            @copy($tempPath, $thumbPath);
                            $okThumb = file_exists($thumbPath);
                        }

                        if (!$okResize) {
                            @copy($tempPath, $resizePath);
                            $okResize = file_exists($resizePath);
                        }

                        @unlink($tempPath);

                        if (!$okResize || !$okThumb) {
                            $status = 'No se pudieron generar los archivos resize o thumbnail.';
                            $statusClass = 'error';
                        } else {
                            $fotoDb = (string)$timeUnix;
                            $extDb = '.' . $ext;
                            $carpetaDb = $carpeta;

                            $sql = "UPDATE notas SET foto = ?, ext_img = ?, carpetafoto = ? WHERE ID = ? LIMIT 1";
                            $stmt = $conn->prepare($sql);

                            if (!$stmt) {
                                $status = 'Error al preparar UPDATE: ' . $conn->error;
                                $statusClass = 'error';
                            } else {
                                $stmt->bind_param('sssi', $fotoDb, $extDb, $carpetaDb, $ID);
                                $okDb = $stmt->execute();
                                $errDb = $stmt->error;
                                $stmt->close();

                                if ($okDb) {
                                    $status = 'Imagen subida correctamente.';
                                    $statusClass = 'ok';
                                } else {
                                    $status = 'La imagen subió pero falló la base de datos: ' . $errDb;
                                    $statusClass = 'error';
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/* =========================================================
   DATOS ACTUALES
   ========================================================= */
$nota = cargarNota($conn, $ID);
$fotoActual = trim((string)$nota['foto']);
$extActual = trim((string)$nota['ext_img']);
$carpetaActual = trim((string)$nota['carpetafoto']);

$previewUrl = '';
$resizeUrl = '';
$previewExists = false;

if ($fotoActual !== '' && $extActual !== '' && $carpetaActual !== '') {
    $previewUrl = '../' . $carpetaActual . '/thumbnail_' . $fotoActual . $extActual;
    $resizeUrl  = '../' . $carpetaActual . '/resize_' . $fotoActual . $extActual;

    $previewFs = $siteRoot . DIRECTORY_SEPARATOR . $carpetaActual . DIRECTORY_SEPARATOR . 'thumbnail_' . $fotoActual . $extActual;
    $previewExists = file_exists($previewFs);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo isset($nombresitio) ? h((string)$nombresitio) : 'Panel'; ?> - Subir foto</title>
<style>
*{box-sizing:border-box}
html,body{margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;background:#eef3f8;color:#1e293b}
body{padding:12px}
.wrap{max-width:640px;margin:0 auto}
.card{background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 12px 30px rgba(0,0,0,.08);border:1px solid #dbe4ee}
.head{padding:18px;background:linear-gradient(135deg,#0f172a,#2563eb);color:#fff}
.head h1{margin:0;font-size:22px;line-height:1.2}
.head p{margin:6px 0 0 0;font-size:14px;opacity:.95}
.body{padding:16px}
.preview{margin-bottom:16px}
.preview img{display:block;width:100%;max-height:340px;object-fit:contain;border-radius:14px;border:1px solid #d8e2ee;background:#f8fafc}
.empty{padding:28px 14px;border:2px dashed #cbd5e1;border-radius:14px;background:#f8fafc;color:#64748b;text-align:center}
.group{margin-bottom:14px}
.label{display:block;font-size:14px;font-weight:700;margin-bottom:8px}
.filebox{padding:14px;border:2px dashed #cbd5e1;border-radius:14px;background:#f8fafc}
input[type=file]{width:100%;font-size:14px}
.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px}
.btn{border:0;text-decoration:none;cursor:pointer;border-radius:12px;padding:14px 16px;font-size:15px;font-weight:700;text-align:center}
.primary{background:#2563eb;color:#fff;flex:1 1 180px}
.secondary{background:#e5e7eb;color:#111827;flex:1 1 140px}
.alert{margin-top:16px;padding:14px;border-radius:12px;font-size:14px;line-height:1.45}
.ok{background:#ecfdf5;color:#065f46;border:1px solid #a7f3d0}
.error{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
.meta{margin-top:16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;padding:12px;font-size:13px;line-height:1.6;word-break:break-word}
.links{margin-top:12px}
.links a{display:inline-block;margin-right:10px;color:#2563eb;text-decoration:none;font-weight:700}
.debug{margin-top:16px;background:#0f172a;color:#dbeafe;border-radius:12px;padding:12px;font-size:12px;line-height:1.5;white-space:pre-wrap;word-break:break-word}
@media (max-width:480px){
    body{padding:8px}
    .head h1{font-size:20px}
    .body{padding:12px}
    .btn{width:100%}
}
</style>
</head>
<body>
<div class="wrap">
    <div class="card">
        <div class="head">
            <h1>Subir foto</h1>
            <p>Nota ID <?php echo (int)$ID; ?></p>
        </div>

        <div class="body">
            <div class="preview">
                <?php if ($previewUrl !== '' && $previewExists): ?>
                    <img src="<?php echo h($previewUrl) . '?t=' . time(); ?>" alt="Vista previa">
                <?php else: ?>
                    <div class="empty">Todavía no hay imagen cargada para esta nota.</div>
                <?php endif; ?>
            </div>

            <form action="upload_foto_movil_home.php?ID=<?php echo (int)$ID; ?>" method="post" enctype="multipart/form-data">
                <div class="group">
                    <label class="label" for="archivo">Seleccionar imagen</label>
                    <div class="filebox">
                        <input type="file" name="archivo" id="archivo" accept=".jpg,.jpeg,.png,.gif,.webp,image/*" required>
                    </div>
                </div>

                <input type="hidden" name="action" value="upload">

                <div class="actions">
                    <button type="submit" class="btn primary">Subir imagen</button>
                    <a href="notas.php" class="btn secondary">Volver</a>
                </div>
            </form>

            <?php if ($status !== ''): ?>
                <div class="alert <?php echo h($statusClass); ?>">
                    <?php echo h($status); ?>
                </div>
            <?php endif; ?>

            <div class="meta">
                Thumbnail: ancho máximo 600px, sin recorte.<br>
                Resize: ancho máximo 1600px, sin recorte.<br>
                Se mantiene siempre la proporción original.<br>
                Carpeta física: <?php echo h($uploadDir); ?><br>
                Foto DB: <?php echo h($fotoActual); ?><br>
                Extensión DB: <?php echo h($extActual); ?><br>
                Carpeta DB: <?php echo h($carpetaActual); ?><br>
                Preview URL: <?php echo h($previewUrl); ?><br>
                Preview existe: <?php echo $previewExists ? 'SI' : 'NO'; ?>
            </div>

            <?php if ($previewUrl !== '' && $previewExists): ?>
                <div class="links">
                    <a href="<?php echo h($previewUrl) . '?t=' . time(); ?>" target="_blank">Ver thumbnail</a>
                    <a href="<?php echo h($resizeUrl) . '?t=' . time(); ?>" target="_blank">Ver resize</a>
                </div>
            <?php endif; ?>

            <?php if (!empty($debug)): ?>
                <div class="debug"><?php echo h(implode("\n", $debug)); ?></div>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>