<?php
// modules/excursions/backend/api/routes.php
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'; // создаёт $pdo

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

// Для PUT-данных
$putData = [];
if ($method === 'PUT') {
    $raw = file_get_contents('php://input');
    $json = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $putData = $json;
    }
}

// --- GET: получить по ID ---
if ($method === 'GET' && $id) {
    $stmt = $pdo->prepare("
      SELECT
        id, name, description, image_url, status,
        country, city, duration_hours, duration_minutes,
        polyline
      FROM routes
      WHERE id = :id
    ");
    $stmt->execute(['id'=>$id]);
    $route = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$route) {
        http_response_code(404);
        echo json_encode(['error'=>'Not found']);
        exit;
    }
    // путь к обложке
    $route['cover_url'] = $route['image_url']
      ? '/uploads/' . basename($route['image_url'])
      : null;
    echo json_encode($route, JSON_UNESCAPED_UNICODE);
    exit;
}

// --- POST: создать новую экскурсию ---
if ($method === 'POST') {
    // собираем данные
    $name    = $_POST['name'] ?? '';
    $desc    = $_POST['description'] ?? '';
    $status  = $_POST['status'] ?? 'draft';
    $country = $_POST['country'] ?? '';
    $city    = $_POST['city'] ?? '';
    $hours   = (int)($_POST['duration_hours']  ?? 0);
    $mins    = (int)($_POST['duration_minutes']?? 0);

    // обработка файла обложки
    $imgUrl = null;
    if (!empty($_FILES['cover_image']['tmp_name'])) {
        $up = __DIR__.'/../../../uploads/';
        if (!file_exists($up)) mkdir($up,0755,true);
        $ext = pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION);
        $fn  = 'route_'.time().'_'.mt_rand(1000,9999).'.'.$ext;
        move_uploaded_file($_FILES['cover_image']['tmp_name'], $up.$fn);
        $imgUrl = '/uploads/'.$fn;
    }

    // вставка
    $fields = ['name','description','status','country','city','duration_hours','duration_minutes'];
    $placeholders = array_map(fn($f)=>":$f",$fields);
    if ($imgUrl) {
      $fields[] = 'image_url';
      $placeholders[] = ':image_url';
    }
    $sql = "INSERT INTO routes (".implode(',',$fields).") VALUES (".implode(',',$placeholders).")";
    $stmt = $pdo->prepare($sql);
    // bind
    $stmt->bindValue(':name',$name);
    $stmt->bindValue(':description',$desc);
    $stmt->bindValue(':status',$status);
    $stmt->bindValue(':country',$country);
    $stmt->bindValue(':city',$city);
    $stmt->bindValue(':duration_hours',$hours,PDO::PARAM_INT);
    $stmt->bindValue(':duration_minutes',$mins,PDO::PARAM_INT);
    if ($imgUrl) $stmt->bindValue(':image_url',$imgUrl);
    $stmt->execute();

    $newId = $pdo->lastInsertId();
    http_response_code(201);
    echo json_encode(['id'=>$newId], JSON_UNESCAPED_UNICODE);
    exit;
}

// --- PUT: обновить только polyline ---
if ($method === 'PUT' && $id) {
    if (empty($putData['polyline']) || !is_array($putData['polyline'])) {
        http_response_code(400);
        echo json_encode(['error'=>'Missing or invalid polyline']);
        exit;
    }
    $polyJson = json_encode($putData['polyline'], JSON_UNESCAPED_UNICODE);
    $stmt = $pdo->prepare("UPDATE routes SET polyline = :poly WHERE id = :id");
    $stmt->execute(['poly'=>$polyJson,'id'=>$id]);
    echo json_encode(['success'=>true], JSON_UNESCAPED_UNICODE);
    exit;
}

// другие методы не поддерживаются
http_response_code(405);
echo json_encode(['error'=>'Method not allowed']);
