<?php
// modules/excursions/backend/api/pois.php
// CRUD API для POI и их переводов

ini_set('display_errors',1);
error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');

require '/home/jwfnsshf/v.centrx.eu/config/db.php';

$method   = $_SERVER['REQUEST_METHOD'];
$route_id = isset($_GET['route_id']) ? (int)$_GET['route_id'] : null;
$id       = isset($_GET['id'])       ? (int)$_GET['id']       : null;

try {
  if ($method === 'GET') {
    if ($route_id) {
      // 1) получаем POI маршрута
      $stmt = $pdo->prepare("
        SELECT id,
               `order` AS poi_order,
               lat,
               lng,
               radius
        FROM pois
        WHERE route_id = :rid
        ORDER BY `order`
      ");
      $stmt->execute(['rid'=>$route_id]);
      $pois = $stmt->fetchAll(PDO::FETCH_ASSOC);

      // 2) получаем переводы через JOIN
      $ids = array_column($pois, 'id');
      if ($ids) {
        $in = implode(',', array_map('intval', $ids));
        $raw = $pdo->query("
          SELECT
            pt.poi_id,
            l.code AS language_code,
            pt.text,
            pt.audio_url,
            pt.image_url
          FROM poi_translations pt
          JOIN languages l ON pt.language_id = l.id
          WHERE pt.poi_id IN ($in)
        ")->fetchAll(PDO::FETCH_ASSOC);
      } else {
        $raw = [];
      }

      // 3) собираем массив переводов
      $translations = [];
      foreach ($raw as $r) {
        $translations[$r['poi_id']][$r['language_code']] = [
          'text'      => $r['text'],
          'audio_url' => $r['audio_url'],
          'image_url' => $r['image_url'],
        ];
      }

      // 4) встраиваем переводы в каждый POI
      foreach ($pois as &$p) {
        $p['translations'] = $translations[$p['id']] ?? [];
      }

      echo json_encode($pois, JSON_UNESCAPED_UNICODE);
      exit;
    }
    if ($id) {
      // Можно добавить GET по отдельному id, если нужно
    }
  }

  if ($method === 'POST') {
    // Создание нового POI
    $routeId = $_POST['route_id'];
    $order   = $_POST['poi_order'];
    $lat     = $_POST['lat'];
    $lng     = $_POST['lng'];
    $radius  = $_POST['radius'];

    $stmt = $pdo->prepare("
      INSERT INTO pois (`route_id`,`order`,lat,lng,radius)
      VALUES (:rid,:ord,:lat,:lng,:rad)
    ");
    $stmt->execute([
      'rid' => $routeId,
      'ord' => $order,
      'lat' => $lat,
      'lng' => $lng,
      'rad' => $radius
    ]);
    $poiId = $pdo->lastInsertId();

    // Загрузка переводов из POST (multipart/form-data)
    $langs = $pdo->query("SELECT id,code FROM languages")->fetchAll(PDO::FETCH_KEY_PAIR);
    foreach ($langs as $langId => $code) {
      $text = $_POST['translations'][$code]['text'] ?? '';
      // аудио
      $audioUrl = '';
      if (!empty($_FILES["audio_$code"]['tmp_name'])) {
        $up = __DIR__ . '/../../../uploads/pois/';
        if (!file_exists($up)) mkdir($up,0755,true);
        $ext = pathinfo($_FILES["audio_$code"]['name'], PATHINFO_EXTENSION);
        $fn  = "poi_{$poiId}_{$code}_audio_".time().".$ext";
        move_uploaded_file($_FILES["audio_$code"]['tmp_name'], $up.$fn);
        $audioUrl = '/uploads/pois/'.$fn;
      }
      // изображение
      $imgUrl = '';
      if (!empty($_FILES["image_$code"]['tmp_name'])) {
        $up = __DIR__ . '/../../../uploads/pois/';
        $ext = pathinfo($_FILES["image_$code"]['name'], PATHINFO_EXTENSION);
        $fn  = "poi_{$poiId}_{$code}_img_".time().".$ext";
        move_uploaded_file($_FILES["image_$code"]['tmp_name'], $up.$fn);
        $imgUrl = '/uploads/pois/'.$fn;
      }
      $stmtT = $pdo->prepare("
        REPLACE INTO poi_translations
          (poi_id,language_id,text,audio_url,image_url)
        VALUES
          (:poi,:lang,:txt,:aud,:img)
      ");
      $stmtT->execute([
        'poi'=>$poiId,
        'lang'=>$langId,
        'txt'=>$text,
        'aud'=>$audioUrl,
        'img'=>$imgUrl
      ]);
    }

    http_response_code(201);
    echo json_encode(['id'=>$poiId], JSON_UNESCAPED_UNICODE);
    exit;
  }

  if ($method === 'PUT' && $id) {
    // Аналогично обновлению pois и poi_translations (можем добавить по требованию)
  }

  if ($method === 'DELETE' && $id) {
    $pdo->prepare("DELETE FROM pois WHERE id=:id")
        ->execute(['id'=>$id]);
    http_response_code(204);
    exit;
  }

  http_response_code(405);
  echo json_encode(['error'=>'Method not allowed']);

} catch (Exception $e) {
  http_response_code(500);
  echo json_encode(['error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
