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

$user = auth_required();

$page  = max(1, (int)($_GET['page'] ?? 1));
$limit = 50;
$offset = ($page - 1) * $limit;

$where  = ['1=1'];
$params = [];

if (!empty($_GET['zone'])) {
    $where[]  = 'p.zone = ?';
    $params[] = $_GET['zone'];
}
if (!empty($_GET['ward'])) {
    $where[]  = 's.ward_no = ?';
    $params[] = $_GET['ward'];
}
if (!empty($_GET['date_from'])) {
    $where[]  = 's.survey_date >= ?';
    $params[] = $_GET['date_from'];
}
if (!empty($_GET['date_to'])) {
    $where[]  = 's.survey_date <= ?';
    $params[] = $_GET['date_to'];
}

// Surveyors see only their own
if ($user['role'] === 'surveyor') {
    $where[]  = 's.surveyor_id = ?';
    $params[] = $user['id'];
}

$sql = 'SELECT s.id, s.survey_date, s.owner_name, s.ward_no, s.tole,
               s.sync_status, s.created_at,
               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 ' . implode(' AND ', $where) . '
        ORDER BY s.created_at DESC
        LIMIT ' . $limit . ' OFFSET ' . $offset;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$countSql = 'SELECT COUNT(*) FROM surveys s LEFT JOIN parcels p ON p.id = s.parcel_id WHERE ' . implode(' AND ', $where);
$cStmt = $pdo->prepare($countSql);
$cStmt->execute($params);

echo json_encode([
    'data'  => $stmt->fetchAll(),
    'total' => (int)$cStmt->fetchColumn(),
    'page'  => $page,
]);
