<?php
require_once __DIR__ . '/../../config/cors.php';
require_once __DIR__ . '/../../config/jwt.php';

$user = auth_required();

$id = (int)($_GET['id'] ?? 0);
if (!$id) { http_response_code(400); echo json_encode(['error' => 'id required']); exit; }

$stmt = $pdo->prepare('
    SELECT s.*, p.parcel_no, p.zone, p.sheet_number, sv.name AS surveyor_name
    FROM surveys s
    LEFT JOIN parcels p  ON p.id = s.parcel_id
    LEFT JOIN surveyors sv ON sv.id = s.surveyor_id
    WHERE s.id = ?
');
$stmt->execute([$id]);
$row = $stmt->fetch();

if (!$row) { http_response_code(404); echo json_encode(['error' => 'Not found']); exit; }

// Add legacy photo URLs
foreach (['owner_photo', 'citizenship_photo', 'land_photo', 'structure_photo'] as $f) {
    if ($row[$f]) $row[$f . '_url'] = UPLOAD_URL . $row[$f];
}

// Load v2: land_owners
$os = $pdo->prepare('SELECT * FROM land_owners WHERE survey_id = ? ORDER BY sequence_order');
$os->execute([$id]);
$row['land_owners'] = $os->fetchAll();
foreach ($row['land_owners'] as &$o) {
    foreach (['owner_photo', 'citizenship_photo', 'land_photo'] as $f) {
        if ($o[$f]) $o[$f . '_url'] = UPLOAD_URL . $o[$f];
    }
}

// Load v2: survey_structures
$ss = $pdo->prepare('SELECT * FROM survey_structures WHERE survey_id = ? ORDER BY sequence_order');
$ss->execute([$id]);
$row['structures'] = $ss->fetchAll();
foreach ($row['structures'] as &$s) {
    foreach (['structure_photo', 'structure_photo_2', 'structure_photo_3', 'structure_photo_4'] as $f) {
        if (!empty($s[$f])) $s[$f . '_url'] = UPLOAD_URL . $s[$f];
    }
}
unset($s);

// Load v2: survey_households
$hs = $pdo->prepare('SELECT * FROM survey_households WHERE survey_id = ? ORDER BY sequence_order');
$hs->execute([$id]);
$row['households'] = $hs->fetchAll();

echo json_encode($row);
