<?php
// updatedevices.php
// Mode A (direct call): returns JSON
// Mode B (included): does not echo/exit

$__included = isset($__UPDATED_FROM_INCLUDE) && $__UPDATED_FROM_INCLUDE === true;

if (!$__included) {
    header('Content-Type: application/json');
}

$response = ['status' => 'error', 'message' => 'Invalid request'];

try {
    check_loggedin($pdo);

    // GroupId from include var OR request
    if (isset($groupId) && (int)$groupId > 0) {
        $gid = (int)$groupId;
    } elseif (isset($_GET['GroupId']) && (int)$_GET['GroupId'] > 0) {
        $gid = (int)$_GET['GroupId'];
    } elseif (isset($_POST['GroupId']) && (int)$_POST['GroupId'] > 0) {
        $gid = (int)$_POST['GroupId'];
    } else {
        throw new Exception('GroupId missing');
    }

    // Fetch group
    $stmt = $pdo->prepare('SELECT * FROM `Groups` WHERE GroupId = ?');
    $stmt->execute([$gid]);
    $group = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$group) {
        throw new Exception('Group not found');
    }

    $checklistQuestions = json_decode($group['ChecklistPrepare'], true);
    if (!is_array($checklistQuestions) || !isset($checklistQuestions['ConfigInfo'])) {
        throw new Exception('Invalid checklist data');
    }

    // Company name
    $stmt = $pdo->prepare('
        SELECT Clients.Name
        FROM `Groups`
        INNER JOIN Clients ON Clients.ClientId = `Groups`.ClientId
        WHERE `Groups`.GroupId = ?
    ');
    $stmt->execute([$gid]);
    $companyName = (string)$stmt->fetchColumn();

    $departmentName = (string)$group['Name']; // group name

    // Find equipment types present in this group (normalize NULL/0 => 0)
    $stmt = $pdo->prepare('
        SELECT DISTINCT COALESCE(NULLIF(EquipmentTypeId, 0), 0) AS EquipmentTypeId
        FROM Devices
        WHERE GroupId = ?
    ');
    $stmt->execute([$gid]);
    $typeIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
    if (empty($typeIds)) {
        $typeIds = [0];
    }

    // Device API endpoint
    $apiUrl = 'http://localhost:6060/SetOfflineConfigInfoForDevices/100?UserName=' . urlencode($login_user['UserName']);

    $sentBatches = 0;
    $batchInfo = [];

    foreach ($typeIds as $typeId) {

        // Devices for this equipment type (and version filter)
        if ($typeId === 0) {
            $stmt = $pdo->prepare('
                SELECT DeviceId
                FROM Devices
                WHERE GroupId = :GroupId
                  AND (EquipmentTypeId IS NULL OR EquipmentTypeId = 0)
                  AND SoftwareVersion > :SoftwareVersion
            ');
        } else {
            $stmt = $pdo->prepare('
                SELECT DeviceId
                FROM Devices
                WHERE GroupId = :GroupId
                  AND EquipmentTypeId = :EquipmentTypeId
                  AND SoftwareVersion > :SoftwareVersion
            ');
            $stmt->bindValue(':EquipmentTypeId', $typeId, PDO::PARAM_INT);
        }

        $stmt->bindValue(':GroupId', $gid, PDO::PARAM_INT);
        $stmt->bindValue(':SoftwareVersion', '20240412.2332');
        $stmt->execute();
        $deviceIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));

        // No devices in this bucket -> skip
        if (empty($deviceIds)) {
            continue;
        }

        // Operators applicable to THIS equipment type
        // Include operator if:
        // - in OperatorGroups for group
        // - AND (no equipment restriction rows exist for this operator/group OR a row exists for this type)
        $stmt = $pdo->prepare('
            SELECT o.*
            FROM OperatorGroups og
            INNER JOIN Operators o ON o.OperatorId = og.OperatorId
            WHERE og.GroupId = :GroupId
              AND (
                    NOT EXISTS (
                        SELECT 1
                        FROM OperatorEquipmentType oe
                        WHERE oe.OperatorId = o.OperatorId
                          AND oe.GroupId = og.GroupId
                    )
                    OR EXISTS (
                        SELECT 1
                        FROM OperatorEquipmentType oe
                        WHERE oe.OperatorId = o.OperatorId
                          AND oe.GroupId = og.GroupId
                          AND oe.EquipmentTypeId = :EquipmentTypeId
                    )
                  )
        ');
        $stmt->bindValue(':GroupId', $gid, PDO::PARAM_INT);
        $stmt->bindValue(':EquipmentTypeId', $typeId, PDO::PARAM_INT);
        $stmt->execute();
        $operators = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $formattedOperators = array_map(function($operator) {
            return [
                "Enable"       => (int)$operator['Enable'],
                "SkipList"     => (int)$operator['SkipList'],
                "ResetCycle"   => (int)$operator['ResetChecklist'],
                "EnablePasswd" => 0,
                "UserName"     => $operator['UserName'],
                "PassWd"       => $operator['Password'],
                "UserID"       => $operator['PINCode']
            ];
        }, $operators);

        $formattedDevices = array_map(function($id) {
            return ["DeviceID" => (int)$id];
        }, $deviceIds);

        // Build payload per equipment type
        $cfg = $checklistQuestions['ConfigInfo'];
        // Your sample JSON shows Config.checkList, but your code uses ConfigInfo.checkList
        // Keep your existing structure:
        $cfg['checkList']['CheckUserArray'] = $formattedOperators;
        $cfg['checkList']['UserNum']        = count($formattedOperators);
        $cfg['checkList']['CompanyName']    = $companyName;
        $cfg['checkList']['Department']     = $departmentName;

        $payload = [
            'ConfigInfo'  => $cfg,
            'DevicesList' => $formattedDevices
        ];

        // Save the last sent payload snapshot (optional) - still per group, so overwrite is fine
        $stmt = $pdo->prepare("UPDATE `Groups` SET ChecklistSent = :ChecklistSent WHERE GroupId = :GroupId");
        $stmt->bindValue(':ChecklistSent', json_encode($payload));
        $stmt->bindValue(':GroupId', $gid, PDO::PARAM_INT);
        $stmt->execute();

        // Send to device API
        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

        $apiResponse = curl_exec($ch);
        $apiStatus   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr     = curl_error($ch);
        curl_close($ch);

        if ($apiResponse === false) {
            throw new Exception('cURL failed: ' . $curlErr);
        }
        if ($apiStatus !== 200) {
            throw new Exception('Device API error (HTTP ' . $apiStatus . '): ' . $apiResponse);
        }

        $sentBatches++;
        $batchInfo[] = [
            'EquipmentTypeId' => $typeId,
            'devices' => count($deviceIds),
            'operators' => count($formattedOperators)
        ];
    }

    $response = [
        'status'  => 'success',
        'message' => 'Data sent to devices successfully',
        'groupId' => $gid,
        'batches' => $sentBatches,
        'details' => $batchInfo
    ];

} catch (Exception $e) {
    $response = ['status' => 'error', 'message' => $e->getMessage()];
}

if (!$__included) {
    echo json_encode($response);
}