<?php
require_once '../src/AccessToken.php';
require_once '../src/Database.php';
$conn = Database::getInstance();

 $user_id = $_GET['user_id'] ?? 0;
 
// Get Bitrix24 user ID from users table
function getBitrixUserIdById($id) {
    global $conn;
    $id = intval($id);
    $sql = "SELECT bitrix24_user_id FROM users WHERE id = $id";
    $res = $conn->query($sql);
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        return $row['bitrix24_user_id'];
    }
    return null;
}

$bitrix24_user = getBitrixUserIdById($user_id);
 
$tokenData = AccessToken::getAccessTokenByUserId($bitrix24_user);
$accessToken = $tokenData['access_token'];
$clientEndPoint = $tokenData['client_endpoint'];
$responsibleId = $tokenData['repo_id'];

// Update status in external_ticket table
function updateExternalTicketStatus($conn, $taskId, $ticketUserId, $newStatus,$stageColor) {
    $sql = "UPDATE external_ticket SET status = ?,stage_color=? WHERE task_id = ? AND ticket_user_id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return "Prepare failed: " . $conn->error;

    $stmt->bind_param("ssii", $newStatus,$stageColor, $taskId, $ticketUserId);
    $stmt->execute();
    $stmt->close();
}

// Fetch from external_ticket table with user details
$sql = "
    SELECT * FROM external_ticket WHERE ticket_user_id = ? ";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $row['task_id'] = !empty($row['task_id']) ? $row['task_id'] : '';

        if (!empty($row['task_id'])) {
            $bitrix_api_url = $clientEndPoint . "tasks.task.get.json?auth=" . $accessToken . "&id=" . $row['task_id'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $bitrix_api_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $bitrix_response = curl_exec($ch);
            curl_close($ch);

            $taskData = json_decode($bitrix_response, true);
             
            
                    if (!isset($taskData['result']['task']['stageId'])) {
                    // Agar stageId na mile to unknown return karo
                    return [
                        'stage_name' => 'New',
                        'stage_color' => '#cccccc'
                    ];
                }

                $stageId = $taskData['result']['task']['stageId'];
                $projectId = $taskData['result']['task']['groupId']; // Project/Workgroup ID

                // Step 2: Get all stages for the project
                $stagesApiUrl = $clientEndPoint . "task.stages.get.json";

                $postData = [
                    'entityId' => $projectId,
                    'auth' => $accessToken
                ];

                $ch2 = curl_init();
                curl_setopt($ch2, CURLOPT_URL, $stagesApiUrl);
                curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch2, CURLOPT_POST, true);
                curl_setopt($ch2, CURLOPT_POSTFIELDS, http_build_query($postData));
                $stagesResponse = curl_exec($ch2);
                curl_close($ch2);

                $stagesData = json_decode($stagesResponse, true);
              
              if (isset($stagesData['result']) && is_array($stagesData['result'])) {
                    foreach ($stagesData['result'] as $stage) {
                         $stages[]=$stage;
                        if ($stage['ID'] == $stageId) {
                            $stageName = $stage['TITLE'];
                            $stageColor = $stage['COLOR'];
                            break;
                        }
                    }
                }
                $UpdateData[]=updateExternalTicketStatus($conn, $row['task_id'], $user_id, $stageName,$stageColor);  
            }
        }
}
 
$conn->close();
header('Content-Type: application/json');
echo json_encode($UpdateData);
 //print_r($UpdateData);
?>