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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stageId = $_POST['stage_id'] ?? 0;
    $bitrixStageId = $_POST['bitrix_stage_id'] ?? 0;
    $bitrixUserId = $_POST['bitrix24_userId'] ?? 0;

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

    $deleteUrl = $domainName . "task.stages.delete.json";
    $postFields = http_build_query([
        "id" => (int)$bitrixStageId,
        "auth" => $accessToken
    ]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $deleteUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        echo "cURL error: $error";
        exit;
    }

    $responseData = json_decode($response, true);

    if (!isset($responseData['result']) || $responseData['result'] !== true) {
        echo "Failed to delete stage from Bitrix24: " . ($responseData['error_description'] ?? 'Unknown error');
        exit;
    }

    $stmt = $conn->prepare("DELETE FROM project_stage WHERE id = ?");
    $stmt->bind_param("i", $stageId);
    if ($stmt->execute()) {
        echo "Stage deleted successfully from Bitrix24 and database.";
    } else {
        echo "Bitrix24 deleted, but DB delete failed: " . $stmt->error;
    }
}
?>
