<?php
session_start();

if (!isset($_SESSION['panel_logged_in']) || $_SESSION['panel_logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

header('Content-Type: application/json');

$sid = $_POST['sid'] ?? '';
$action = $_POST['action'] ?? '';
$comment = $_POST['comment'] ?? '';

if (!$sid || !$action) {
    echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
    exit;
}

$uploadDir = __DIR__ . '/uploaded_images/';
$imagePath = '';

if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $fileTmpPath = $_FILES['image']['tmp_name'];
    $fileName = $_FILES['image']['name'];
    $fileSize = $_FILES['image']['size'];
    $fileType = $_FILES['image']['type'];
    $fileNameCmps = explode(".", $fileName);
    $fileExtension = strtolower(end($fileNameCmps));
    
    $allowedExtensions = array('jpg', 'jpeg', 'png', 'gif', 'webp');
    
    if (in_array($fileExtension, $allowedExtensions)) {
        if ($fileSize < 5000000) {
            $newFileName = $sid . '_' . time() . '.' . $fileExtension;
            $destPath = $uploadDir . $newFileName;
            
            if (move_uploaded_file($fileTmpPath, $destPath)) {
                $imagePath = '/uploaded_images/' . $newFileName;
            } else {
                echo json_encode(['success' => false, 'message' => 'Error al mover el archivo']);
                exit;
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'El archivo es demasiado grande (máx. 5MB)']);
            exit;
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Tipo de archivo no permitido']);
        exit;
    }
}

$sessionsFile = __DIR__ . "/sessions.json";
$sessions = file_exists($sessionsFile) ? json_decode(file_get_contents($sessionsFile), true) : [];

if (!isset($sessions[$sid])) {
    echo json_encode(['success' => false, 'message' => 'Sesión no encontrada']);
    exit;
}

$sessions[$sid]['status'] = $action;

if ($imagePath) {
    $sessions[$sid]['image_path'] = $imagePath;
}

$sessions[$sid]['comment'] = $comment;

if (file_put_contents($sessionsFile, json_encode($sessions, JSON_PRETTY_PRINT)) === false) {
    echo json_encode(['success' => false, 'message' => 'Error al guardar los datos']);
    exit;
}

echo json_encode([
    'success' => true,
    'message' => 'Estado actualizado correctamente',
    'image_path' => $imagePath
]);
