<?php
/**
 * Heritage Voice — tours.php
 * GET    /tours              Danh sách tour của user
 * POST   /tours              Tạo tour mới
 * GET    /tours/{id}         Chi tiết tour + items
 * PUT    /tours/{id}         Sửa thông tin tour
 * DELETE /tours/{id}         Xóa tour
 * POST   /tours/{id}/items           Thêm item vào tour
 * PUT    /tours/{id}/items/{item_id} Sửa item
 * DELETE /tours/{id}/items/{item_id} Xóa item
 * POST   /tours/{id}/reorder         Sắp xếp lại items
 * POST   /tours/{id}/items/{item_id}/booking Gắn booking vào item
 */

function tours_list(): void {
    $u = require_auth();
    $rows = db()->prepare("
        SELECT t.*, COUNT(i.id) AS item_count
        FROM hv_user_tours t
        LEFT JOIN hv_tour_items i ON i.tour_id = t.id
        WHERE t.user_id = :uid
        GROUP BY t.id
        ORDER BY t.updated_at DESC
    ");
    $rows->execute([':uid' => $u['id']]);
    $tours = $rows->fetchAll();
    foreach ($tours as &$t) {
        $t['id']         = (int)$t['id'];
        $t['item_count'] = (int)$t['item_count'];
    }
    json_ok($tours);
}

function tours_create(): void {
    $u = require_auth();
    $b = body();
    $name       = trim($b['name'] ?? 'Tour của tôi');
    $start_date = trim($b['start_date'] ?? '');
    $notes      = trim($b['notes'] ?? '');
    $stmt = db()->prepare("INSERT INTO hv_user_tours (user_id,name,start_date,notes) VALUES (:uid,:n,:d,:no)");
    $stmt->execute([':uid'=>$u['id'],':n'=>$name,':d'=>$start_date?:null,':no'=>$notes?:null]);
    $id = (int)db()->lastInsertId();
    json_ok(['id'=>$id,'name'=>$name,'start_date'=>$start_date,'item_count'=>0]);
}

function tours_get(string $id): void {
    $u = require_auth();
    $t = db()->prepare("SELECT * FROM hv_user_tours WHERE id=:id AND user_id=:uid");
    $t->execute([':id'=>$id,':uid'=>$u['id']]);
    $tour = $t->fetch();
    if (!$tour) json_error('Tour không tồn tại', 404);
    $items = db()->prepare("SELECT * FROM hv_tour_items WHERE tour_id=:id ORDER BY order_idx ASC");
    $items->execute([':id'=>$id]);
    $tour['items'] = $items->fetchAll();
    $tour['id'] = (int)$tour['id'];
    foreach ($tour['items'] as &$item) $item['id'] = (int)$item['id'];
    json_ok($tour);
}

function tours_update(string $id): void {
    $u = require_auth();
    $b = body();
    $fields = []; $params = [':id'=>$id,':uid'=>$u['id']];
    if (isset($b['name']))       { $fields[]='name=:n';       $params[':n']=$b['name']; }
    if (isset($b['start_date'])) { $fields[]='start_date=:d'; $params[':d']=$b['start_date']?:null; }
    if (isset($b['notes']))      { $fields[]='notes=:no';     $params[':no']=$b['notes']; }
    if (!$fields) json_error('Không có gì để cập nhật', 400);
    db()->prepare("UPDATE hv_user_tours SET ".implode(',',$fields)." WHERE id=:id AND user_id=:uid")
        ->execute($params);
    json_ok(['message'=>'Đã cập nhật']);
}

function tours_delete(string $id): void {
    $u = require_auth();
    $t = db()->prepare("SELECT id FROM hv_user_tours WHERE id=:id AND user_id=:uid");
    $t->execute([':id'=>$id,':uid'=>$u['id']]);
    if (!$t->fetch()) json_error('Tour không tồn tại', 404);
    db()->prepare("DELETE FROM hv_user_tours WHERE id=:id")->execute([':id'=>$id]);
    json_ok(['message'=>'Đã xóa tour']);
}

function tours_add_item(string $tourId): void {
    $u = require_auth();
    $t = db()->prepare("SELECT id FROM hv_user_tours WHERE id=:id AND user_id=:uid");
    $t->execute([':id'=>$tourId,':uid'=>$u['id']]);
    if (!$t->fetch()) json_error('Tour không tồn tại', 404);
    $b = body();
    $type      = in_array($b['type']??'',['site','partner']) ? $b['type'] : 'site';
    $ref_id    = trim($b['ref_id']??'');
    $ref_name  = trim($b['ref_name']??'');
    $ref_image = trim($b['ref_image']??'');
    $time      = trim($b['custom_time']??'');
    $note      = trim($b['custom_note']??'');
    if (!$ref_id) json_error('Thiếu ref_id', 400);
    // Lấy order_idx tiếp theo
    $mx = db()->prepare("SELECT COALESCE(MAX(order_idx),0)+1 AS nx FROM hv_tour_items WHERE tour_id=:id");
    $mx->execute([':id'=>$tourId]);
    $next = (int)$mx->fetch()['nx'];
    $stmt = db()->prepare("INSERT INTO hv_tour_items (tour_id,order_idx,type,ref_id,ref_name,ref_image,custom_time,custom_note) VALUES (:tid,:ord,:t,:rid,:rn,:ri,:tm,:no)");
    $stmt->execute([':tid'=>$tourId,':ord'=>$next,':t'=>$type,':rid'=>$ref_id,':rn'=>$ref_name,':ri'=>$ref_image,':tm'=>$time?:null,':no'=>$note?:null]);
    json_ok(['id'=>(int)db()->lastInsertId(),'order_idx'=>$next]);
}

function tours_update_item(string $tourId, string $itemId): void {
    $u = require_auth();
    $t = db()->prepare("SELECT t.id FROM hv_tour_items i JOIN hv_user_tours t ON t.id=i.tour_id WHERE i.id=:iid AND t.id=:tid AND t.user_id=:uid");
    $t->execute([':iid'=>$itemId,':tid'=>$tourId,':uid'=>$u['id']]);
    if (!$t->fetch()) json_error('Item không tồn tại', 404);
    $b = body(); $fields=[]; $params=[':id'=>$itemId];
    if (isset($b['custom_time'])) { $fields[]='custom_time=:tm'; $params[':tm']=$b['custom_time']?:null; }
    if (isset($b['custom_note'])) { $fields[]='custom_note=:no'; $params[':no']=$b['custom_note']?:null; }
    if (isset($b['ref_name']))    { $fields[]='ref_name=:rn';    $params[':rn']=$b['ref_name']; }
    if (!$fields) json_error('Không có gì để cập nhật', 400);
    db()->prepare("UPDATE hv_tour_items SET ".implode(',',$fields)." WHERE id=:id")->execute($params);
    json_ok(['message'=>'Đã cập nhật']);
}

function tours_delete_item(string $tourId, string $itemId): void {
    $u = require_auth();
    $t = db()->prepare("SELECT i.id FROM hv_tour_items i JOIN hv_user_tours t ON t.id=i.tour_id WHERE i.id=:iid AND t.id=:tid AND t.user_id=:uid");
    $t->execute([':iid'=>$itemId,':tid'=>$tourId,':uid'=>$u['id']]);
    if (!$t->fetch()) json_error('Item không tồn tại', 404);
    db()->prepare("DELETE FROM hv_tour_items WHERE id=:id")->execute([':id'=>$itemId]);
    json_ok(['message'=>'Đã xóa']);
}

function tours_reorder(string $tourId): void {
    $u = require_auth();
    $t = db()->prepare("SELECT id FROM hv_user_tours WHERE id=:id AND user_id=:uid");
    $t->execute([':id'=>$tourId,':uid'=>$u['id']]);
    if (!$t->fetch()) json_error('Tour không tồn tại', 404);
    $b = body();
    $order = $b['order'] ?? []; // [{id:1,order_idx:0},{id:2,order_idx:1}...]
    $stmt = db()->prepare("UPDATE hv_tour_items SET order_idx=:ord WHERE id=:id AND tour_id=:tid");
    foreach ($order as $item) {
        $stmt->execute([':ord'=>(int)$item['order_idx'],':id'=>(int)$item['id'],':tid'=>$tourId]);
    }
    json_ok(['message'=>'Đã sắp xếp']);
}

function tours_attach_booking(string $tourId, string $itemId): void {
    $u = require_auth();
    $t = db()->prepare("SELECT i.id FROM hv_tour_items i JOIN hv_user_tours t ON t.id=i.tour_id WHERE i.id=:iid AND t.id=:tid AND t.user_id=:uid");
    $t->execute([':iid'=>$itemId,':tid'=>$tourId,':uid'=>$u['id']]);
    if (!$t->fetch()) json_error('Item không tồn tại', 404);
    $b = body();
    $ref    = trim($b['booking_ref']??'');
    $status = trim($b['booking_status']??'pending');
    if (!$ref) json_error('Thiếu booking_ref', 400);
    db()->prepare("UPDATE hv_tour_items SET booking_ref=:r,booking_status=:s WHERE id=:id")
        ->execute([':r'=>$ref,':s'=>$status,':id'=>$itemId]);
    json_ok(['message'=>'Đã gắn booking']);
}
