<?php
header('Content-Type: application/json');
require_once 'config.php';

try {
    $db = getDB();

    // Get filter parameters
    $search = isset($_GET['search']) ? '%' . $_GET['search'] . '%' : '';
    $from_date = isset($_GET['from_date']) ? $_GET['from_date'] : '';
    $to_date = isset($_GET['to_date']) ? $_GET['to_date'] : '';
    $condition_status = isset($_GET['condition_status']) ? $_GET['condition_status'] : '';

    // Build dynamic WHERE clause
    $where_clauses = [];
    $params = [];

    if ($search !== '%' && $search !== '%') {
        $where_clauses[] = '(name LIKE ?)';
        $params[] = $search;
    }

    if ($from_date) {
        $where_clauses[] = '(DATE(created_at) >= ?)';
        $params[] = $from_date;
    }

    if ($to_date) {
        $where_clauses[] = '(DATE(created_at) <= ?)';
        $params[] = $to_date;
    }

    if ($condition_status) {
        $where_clauses[] = '(condition_status = ?)';
        $params[] = $condition_status;
    }

    // Build SQL query
    $sql = 'SELECT id, name, road_type, coordinates, length_meters, condition_status, created_at, updated_at FROM roads';

    if (count($where_clauses) > 0) {
        $sql .= ' WHERE ' . implode(' AND ', $where_clauses);
    }

    $sql .= ' ORDER BY created_at DESC';

    // Execute query
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $roads = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Decode coordinates JSON for each road
    foreach ($roads as &$road) {
        $road['coordinates'] = json_decode($road['coordinates'], true);
    }

    // Count total for unfiltered query
    $count_sql = 'SELECT COUNT(*) as total FROM roads' . (count($where_clauses) > 0 ? ' WHERE ' . implode(' AND ', $where_clauses) : '');
    $count_stmt = $db->prepare($count_sql);
    $count_stmt->execute($params);
    $total = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];

    // Prepare filters applied info
    $filters_applied = [];
    if ($search !== '%' && $search !== '%') {
        $filters_applied['search'] = str_replace('%', '', $search);
    }
    if ($from_date || $to_date) {
        $filters_applied['date_range'] = [];
        if ($from_date) $filters_applied['date_range'][] = $from_date;
        if ($to_date) $filters_applied['date_range'][] = $to_date;
    }
    if ($condition_status) {
        $filters_applied['condition_status'] = $condition_status;
    }

    // Return success response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'lines' => $roads,
        'total' => $total,
        'filters_applied' => $filters_applied
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
