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

$user = auth_required();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit;
}

$rawData = $_POST['survey_data'] ?? '';
// Fallback: parse raw multipart stream if $_POST empty
if (empty($rawData)) {
    $raw = file_get_contents('php://input');
    if (preg_match('/name="survey_data"\s*\r?\n\r?\n(.*?)(\r?\n--)/s', $raw, $m)) {
        $rawData = trim($m[1]);
    }
}
$data = json_decode($rawData, true);
if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing or invalid survey_data', 'raw' => substr($rawData, 0, 200)]);
    exit;
}

// ── Server-side cleaners (backstop so DB stays clean even if app bypassed) ─────
function clean_text($v): string {
    $v = trim((string)$v);
    $v = preg_replace('/\s+/u', ' ', $v);          // collapse whitespace
    return $v;
}
function clean_name($v): string {
    $v = (string)$v;
    $v = preg_replace('/[^A-Za-z .\'\-]/', '', $v); // English letters + . \' - space only
    return trim(preg_replace('/\s+/', ' ', $v));
}
function clean_digits($v): string {
    // keep digits and structural separators (citizenship / ward formats)
    return trim(preg_replace('/[^0-9\-\/ ]/', '', (string)$v));
}
function clean_phone($v): string {
    return preg_replace('/[^0-9+]/', '', (string)$v);
}
function clean_ascii($v, int $max = 0): string {
    $v = (string)$v;
    $v = preg_replace('/[^\x20-\x7E\n]/', '', $v);  // printable ASCII + newline
    $v = trim(preg_replace('/[ \t]+/', ' ', $v));
    if ($max > 0 && mb_strlen($v) > $max) $v = mb_substr($v, 0, $max);
    return $v;
}

// Resolve parcel_id from kml_id if parcel_id is 0
$parcelId = (int)($data['parcel_id'] ?? 0);
if ($parcelId === 0 && !empty($data['kml_id'])) {
    $ps = $pdo->prepare('SELECT id FROM parcels WHERE kml_id = ?');
    $ps->execute([$data['kml_id']]);
    $parcelId = (int)($ps->fetchColumn() ?: 0);
}

// ── Duplicate detection ───────────────────────────────────────────────────────
// Flag (but don't block) if this parcel already has a synced survey
$isDuplicate = false;
if ($parcelId > 0) {
    $dupCheck = $pdo->prepare(
        "SELECT COUNT(*) FROM surveys WHERE parcel_id = ? AND sync_status = 'synced'"
    );
    $dupCheck->execute([$parcelId]);
    $isDuplicate = (int)$dupCheck->fetchColumn() > 0;
}

// ── Photo helper ──────────────────────────────────────────────────────────────
function savePhoto(string $field, int $surveyorId): string {
    if (!isset($_FILES[$field]) || $_FILES[$field]['error'] !== UPLOAD_ERR_OK) return '';
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) return '';
    $name = "{$field}_{$surveyorId}_" . time() . mt_rand(100, 999) . ".$ext";
    $dest = UPLOAD_DIR . $name;
    if (!is_dir(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);
    move_uploaded_file($_FILES[$field]['tmp_name'], $dest);
    return $name;
}

// ── Legacy photos (backward compat) ──────────────────────────────────────────
$ownerPhoto       = savePhoto('owner_photo',       $user['id']);
$citizenshipPhoto = savePhoto('citizenship_photo', $user['id']);
$landPhoto        = savePhoto('land_photo',        $user['id']);
$structurePhoto   = savePhoto('structure_photo',   $user['id']);

// ── Insert main survey row ────────────────────────────────────────────────────
$stmt = $pdo->prepare('
    INSERT INTO surveys (
        parcel_id, surveyor_id, ward_no, tole, survey_date, gps_lat, gps_lng,
        owner_name, citizenship_no, owner_photo, citizenship_photo, land_photo,
        land_type, ownership_type,
        structure_type, structure_type_other, construction_material,
        num_floors, floor_length_m, floor_breadth_m, year_built, structure_condition,
        is_occupied, is_rented, monthly_rent, num_rooms, structure_photo,
        hoh_name, contact_no, hoh_citizenship, total_members, families_count,
        vulnerability_flags, residence_status, remarks, sync_status
    ) VALUES (
        :parcel_id, :surveyor_id, :ward_no, :tole, :survey_date, :gps_lat, :gps_lng,
        :owner_name, :citizenship_no, :owner_photo, :citizenship_photo, :land_photo,
        :land_type, :ownership_type,
        :structure_type, :structure_type_other, :construction_material,
        :num_floors, :floor_length_m, :floor_breadth_m, :year_built, :structure_condition,
        :is_occupied, :is_rented, :monthly_rent, :num_rooms, :structure_photo,
        :hoh_name, :contact_no, :hoh_citizenship, :total_members, :families_count,
        :vulnerability_flags, :residence_status, :remarks, "synced"
    )
');
$stmt->execute([
    'parcel_id'            => $parcelId,
    'surveyor_id'          => $user['id'],
    'ward_no'              => clean_digits($data['ward_no'] ?? ''),
    'tole'                 => clean_text($data['tole'] ?? ''),
    'survey_date'          => $data['survey_date'] ?? date('Y-m-d'),
    'gps_lat'              => $data['gps_lat'] ?? 0,
    'gps_lng'              => $data['gps_lng'] ?? 0,
    'owner_name'           => clean_name($data['owner_name'] ?? ''),
    'citizenship_no'       => clean_digits($data['citizenship_no'] ?? ''),
    'owner_photo'          => $ownerPhoto,
    'citizenship_photo'    => $citizenshipPhoto,
    'land_photo'           => $landPhoto,
    'land_type'            => clean_ascii($data['land_type'] ?? '', 80),
    'ownership_type'       => clean_ascii($data['ownership_type'] ?? '', 80),
    'structure_type'       => $data['structure_type'] ?? '',
    'structure_type_other' => clean_ascii($data['structure_type_other'] ?? '', 100),
    'construction_material'=> clean_ascii($data['construction_material'] ?? '', 200),
    'num_floors'           => (int)($data['num_floors'] ?? 0),
    'floor_length_m'       => $data['floor_length_m'] ?? 0,
    'floor_breadth_m'      => $data['floor_breadth_m'] ?? 0,
    'year_built'           => (int)($data['year_built'] ?? 0),
    'structure_condition'  => $data['structure_condition'] ?? '',
    'is_occupied'          => (int)($data['is_occupied'] ?? 0),
    'is_rented'            => (int)($data['is_rented'] ?? 0),
    'monthly_rent'         => $data['monthly_rent'] ?? 0,
    'num_rooms'            => (int)($data['num_rooms'] ?? 0),
    'structure_photo'      => $structurePhoto,
    'hoh_name'             => clean_name($data['hoh_name'] ?? ''),
    'contact_no'           => clean_phone($data['contact_no'] ?? ''),
    'hoh_citizenship'      => clean_digits($data['hoh_citizenship'] ?? ''),
    'total_members'        => (int)($data['total_members'] ?? 0),
    'families_count'       => (int)($data['families_count'] ?? 0),
    'vulnerability_flags'  => $data['vulnerability_flags'] ?? '',
    'residence_status'     => $data['residence_status'] ?? '',
    'remarks'              => clean_ascii($data['remarks'] ?? '', 500),
]);

$surveyId = (int)$pdo->lastInsertId();

// ── v2: Insert land_owners ────────────────────────────────────────────────────
$landOwners = $data['land_owners'] ?? [];
if (!empty($landOwners)) {
    $ownerStmt = $pdo->prepare('
        INSERT INTO land_owners
            (survey_id, owner_name, citizenship_no, ownership_share_pct,
             owner_photo, citizenship_photo, land_photo, is_primary, sequence_order)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ');
    foreach ($landOwners as $i => $o) {
        $oPhoto  = savePhoto("owner_photo_$i",       $user['id']);
        $cPhoto  = savePhoto("citizenship_photo_$i", $user['id']);
        $lPhoto  = savePhoto("land_photo_$i",        $user['id']);
        // Fallback: use legacy photos for index 0 if indexed ones empty
        if ($i === 0) {
            if (!$oPhoto) $oPhoto = $ownerPhoto;
            if (!$cPhoto) $cPhoto = $citizenshipPhoto;
            if (!$lPhoto) $lPhoto = $landPhoto;
        }
        $ownerStmt->execute([
            $surveyId,
            clean_name($o['name'] ?? ''),
            clean_digits($o['citizenshipNo'] ?? ''),
            max(0, min(100, (int)($o['sharePercent'] ?? 100))),
            $oPhoto,
            $cPhoto,
            $lPhoto,
            (int)($o['isPrimary'] ?? ($i === 0 ? 1 : 0)),
            $i + 1
        ]);
    }
}

// ── v2: Insert survey_structures ──────────────────────────────────────────────
$structures = $data['survey_structures'] ?? [];
if (!empty($structures)) {
    $structStmt = $pdo->prepare('
        INSERT INTO survey_structures
            (survey_id, structure_type, structure_type_other, construction_material,
             num_floors, floor_length_m, floor_breadth_m, year_built, structure_condition,
             is_occupied, is_rented, monthly_rent, num_rooms,
             structure_photo, structure_photo_2, structure_photo_3, structure_photo_4,
             owner_type, structure_owner_name, structure_owner_citizenship, sequence_order)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ');
    foreach ($structures as $i => $s) {
        $sPhoto  = savePhoto("structure_photo_$i",    $user['id']);   // side 1
        $sPhoto2 = savePhoto("structure_photo_{$i}_2", $user['id']);
        $sPhoto3 = savePhoto("structure_photo_{$i}_3", $user['id']);
        $sPhoto4 = savePhoto("structure_photo_{$i}_4", $user['id']);
        if ($i === 0 && !$sPhoto) $sPhoto = $structurePhoto;
        $structStmt->execute([
            $surveyId,
            $s['structureType'] ?? 'house',
            clean_ascii($s['structureTypeOther'] ?? '', 100),
            clean_ascii($s['constructionMaterial'] ?? '', 200),
            (int)($s['numFloors'] ?? 0),
            $s['floorLengthM'] ?? 0,
            $s['floorBreadthM'] ?? 0,
            (int)($s['yearBuilt'] ?? 0),
            $s['structureCondition'] ?? 'good',
            (int)($s['isOccupied'] ?? 0),
            (int)($s['isRented'] ?? 0),
            $s['monthlyRent'] ?? 0,
            (int)($s['numRooms'] ?? 0),
            $sPhoto,
            $sPhoto2,
            $sPhoto3,
            $sPhoto4,
            $s['ownerType'] ?? 'land_owner',
            clean_name($s['structureOwnerName'] ?? ''),
            clean_digits($s['structureOwnerCitizenship'] ?? ''),
            $i + 1
        ]);
    }
}


// ── Mark parcel completed ─────────────────────────────────────────────────────
// A kitta (sheet_number + parcel_no) may be split across zone rings into several
// polygons, each its own parcels row. Completing one must complete ALL pieces of
// the same kitta, so the surveyor never has to survey the same land twice and the
// other pieces don't stay falsely "pending".
if ($parcelId) {
    $pdo->prepare('UPDATE parcels SET survey_status = "completed" WHERE id = ?')->execute([$parcelId]);

    $pi = $pdo->prepare('SELECT sheet_number, parcel_no FROM parcels WHERE id = ?');
    $pi->execute([$parcelId]);
    $info = $pi->fetch();
    if ($info && $info['sheet_number'] !== '' && $info['sheet_number'] !== null
             && $info['parcel_no'] !== '' && $info['parcel_no'] !== null) {
        $pdo->prepare(
            'UPDATE parcels SET survey_status = "completed"
             WHERE sheet_number = ? AND parcel_no = ? AND survey_status <> "completed"'
        )->execute([$info['sheet_number'], $info['parcel_no']]);
    }
}

echo json_encode([
    'success'      => true,
    'message'      => $isDuplicate ? 'Survey saved (duplicate — parcel already surveyed)' : 'Survey saved',
    'is_duplicate' => $isDuplicate,
    'survey_id'    => $surveyId,
    'owners'       => count($landOwners),
    'structures'   => count($structures),
]);
