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


function getProjectStages($conn, $project_id, $bitrix_user_id) {
    $stages = [];

    $sql = "SELECT * FROM project_stage WHERE project_id = ? AND bitrix_user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $project_id, $bitrix_user_id);

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $stages[] = $row;
        }
    }

    echo json_encode($stages);
}


function insertProjectStage($conn, $data) {
    $stage_name = $data['stage_name'] ?? '';
    $stage_color = $data['stage_color'] ?? 'FF0000'; // default red if empty
    $project_id = $data['project_id'] ?? '';
    $bitrix24_project_id = $data['bitrix_project_id'] ?? '';
    $bitrix_user_id = $data['bitrix_user_id'] ?? '';

    $tokenData = AccessToken::getAccessTokenByUserId($bitrix_user_id);
    $accessToken = $tokenData['access_token'] ?? '';
    $domainName = $tokenData['client_endpoint'] ?? '';

    if (!$accessToken || !$domainName) {
        return "Bitrix24 token or domain not found.";
    }

    // 2. Prepare Bitrix24 API request
    $bitrixFields = [
        "fields" => [
            "TITLE" => $stage_name,
            "COLOR" => strtoupper($stage_color), // make sure color is uppercase
            "ENTITY_ID" => $bitrix24_project_id,
            "AFTER_ID"=>1
        ]
    ];

    $url = $domainName ."task.stages.add.json?auth=" . $accessToken;
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bitrixFields));
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);

    if (!isset($responseData['result']) || $responseData['result'] <= 0) {
    return "Bitrix24 stage creation failed: " . ($responseData['error_description'] ?? 'Unknown error');
}

$bitrix_stage_id = $responseData['result'];

$query = "INSERT INTO project_stage (stage_name, stage_color, bitrix_user_id, project_id, bitrix24_project_id, stage_id) 
          VALUES (?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($query);
if (!$stmt) {
    return "Prepare failed: " . $conn->error;
}

$stmt->bind_param("ssiiii", $stage_name, $stage_color, $bitrix_user_id, $project_id, $bitrix24_project_id, $bitrix_stage_id);

if ($stmt->execute()) {
    return "Stage created successfully in Bitrix24 and saved locally.";
} else {
    return "Bitrix24 stage created, but DB insert failed: " . $stmt->error;
}

}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // INSERT
    $result = insertProjectStage($conn, $_POST);
   
    echo $result;
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // GET STAGES
    $project_id = isset($_GET['project_id']) ? intval($_GET['project_id']) : null;
    $bitrix_user_id = isset($_GET['bitrix_user_id']) ? intval($_GET['bitrix_user_id']) : null;
    $bitrix24_project = isset($_GET['bitrix24_project']) ? intval($_GET['bitrix24_project']) : null;

    if ($project_id && $bitrix_user_id) {
        getProjectStages($conn, $project_id, $bitrix_user_id,$bitrix24_project);
    } else {
        echo json_encode([]);
    }
}
?>