<?php
require_once 'Database.php';
require_once 'AccessToken.php';

function syncProjectStages($project_id, $bitrix_user_id, $bitrix_project_id) {
    $tokenData = AccessToken::getAccessTokenByUserId($bitrix_user_id);
    $accessToken = $tokenData['access_token'] ?? '';
    $clientEndpoint = $tokenData['client_endpoint'] ?? '';
    $conn = Database::getInstance();

    if (empty($accessToken) || empty($clientEndpoint)) {
        return ['status' => 'error', 'message' => 'Access token or endpoint missing'];
    }

    $url = $clientEndpoint . "task.stages.get.json?auth=" . $accessToken . "&entityId=" . $bitrix_project_id;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if (!$res || $httpCode !== 200) {
        return ['status' => 'error', 'message' => 'Failed to fetch stages from Bitrix24', 'curl_error' => $curlError, 'http_code' => $httpCode];
    }

    $data = json_decode($res, true);

    if (!isset($data['result'])) {
        return ['status' => 'error', 'message' => 'No stages found in Bitrix response'];
    }
 
    $inserted = 0;
    foreach ($data['result'] as $stage) {
        $stageId = $stage['ID'];

        $checkSql = "SELECT id FROM project_stage WHERE stage_id = ? AND project_id = ?";
        $checkStmt = $conn->prepare($checkSql);
        $checkStmt->bind_param("ii", $stageId, $project_id);
        $checkStmt->execute();
        $checkStmt->store_result();

        if ($checkStmt->num_rows === 0) {
            $insertSql = "INSERT INTO project_stage (stage_name, stage_color, bitrix_user_id, project_id, bitrix24_project_id, stage_id) 
                          VALUES (?, ?, ?, ?, ?, ?)";
            $insertStmt = $conn->prepare($insertSql);
            if (!$insertStmt) {
                return ['status' => 'error', 'message' => 'Insert statement prepare failed'];
            }

            $insertStmt->bind_param("ssiisi", 
                $stage['TITLE'], 
                $stage['COLOR'], 
                $bitrix_user_id, 
                $project_id, 
                $bitrix_project_id, 
                $stageId
            );
            if ($insertStmt->execute()) {
                $inserted++;
            }
            $insertStmt->close();
        }

        $checkStmt->close();
    }

    return ['status' => 'success', 'inserted' => $inserted];
}
