<?php
require_once 'Database.php';

function getProjectsByBitrixUser($bitrixUserId) {
    if (!$bitrixUserId) {
        return ['success' => false, 'error' => 'Missing Bitrix24 user ID'];
    }

    $conn = Database::getInstance();
    $conn->query("SET SESSION group_concat_max_len = 1000000");

    $query = "
        SELECT 
            p.id AS local_project_id,
            p.project_name,
            p.project_id AS bitrix_project_id,
            p.folder_id,
            p.project_type,
            p.flow_type,
            p.query_email,
            GROUP_CONCAT(
                JSON_OBJECT(
                    'name', pr.responsible_name,
                    'id', pr.responsible_bitrix_id
                )
            ) AS responsible_persons_json
        FROM 
            projects p
        LEFT JOIN 
            project_responsible_users pr ON p.id = pr.project_id
        WHERE 
            p.bitrix24_user_id = ?
        GROUP BY 
            p.id
    ";

    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $bitrixUserId);
    $stmt->execute();
    $result = $stmt->get_result();

    $projects = [];
    while ($row = $result->fetch_assoc()) {
        $row['responsible_persons'] = [];

        if (!empty($row['responsible_persons_json'])) {
            // Create full JSON array string
            $jsonArrayString = '[' . $row['responsible_persons_json'] . ']';

            // Decode JSON array safely
            $decodedPersons = json_decode($jsonArrayString, true);
            if (is_array($decodedPersons)) {
                $row['responsible_persons'] = $decodedPersons;
            }
        }

        unset($row['responsible_persons_json']);
        $projects[] = $row;
    }

    $stmt->close();

    return ['success' => true, 'data' => $projects];
}

# Example usage:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $bitrixUserId = $_POST['bitrix_user_id'] ?? null;
    $result = getProjectsByBitrixUser($bitrixUserId);

     echo json_encode($result); // Use this if responding to API call
}
?>
