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

$user_id = $_GET['user_id'] ?? null;
$response = ['success' => false];

if ($user_id) {
    try {
        // Get comp_id from user
        $stmt = $conn->prepare("SELECT comp_id FROM tbl_company_user WHERE comp_id = ?");
        $stmt->execute([$user_id]);
        $company = $stmt->fetch();

        if ($company) {
            $comp_id = $company['comp_id'];

            $stmt = $conn->prepare("
                SELECT 
                    fm.id AS flow_meter_id,
                    fm.meter_name AS flow_meter_name,
                    fm.address,
                    CONCAT(d.water_flow, ' m³/hr') AS flow_rate_with_unit,
                    CONCAT(d.totalizer, ' m³') AS totalizer_with_unit,
                    CONCAT(ROUND(d.totalizer * 1000, 2), ' L') AS totalizer_liters_with_unit,
                    d.created_date
                FROM tbl_flow_meter fm
                LEFT JOIN (
                    SELECT t1.*
                    FROM tbl_flow_meter_data t1
                    INNER JOIN (
                        SELECT flow_meter_id, MAX(created_date) AS max_created
                        FROM tbl_flow_meter_data
                        WHERE flag = 1
                        GROUP BY flow_meter_id
                    ) t2 
                    ON t1.flow_meter_id = t2.flow_meter_id 
                       AND t1.created_date = t2.max_created
                    WHERE t1.flag = 1
                ) d ON fm.id = d.flow_meter_id
                WHERE fm.comp_id = :comp_id
                  AND fm.flag = 0        -- Here flag = 0 for inactive devices
                ORDER BY d.created_date DESC
            ");

            $stmt->execute(['comp_id' => $comp_id]);
            $data = $stmt->fetchAll();

            $response['success'] = true;
            $response['data'] = $data;
        } else {
            $response['error'] = 'Company user not found';
        }
    } catch (PDOException $e) {
        $response['error'] = 'Database error: ' . $e->getMessage();
    }
} else {
    $response['message'] = 'Missing user_id parameter';
}

echo json_encode($response);
