<?php

if ( !$user['superAdmin'] ) {
    session_start();
    $_SESSION['error'] = 'Unauthorized';

    header('Location: '.URL_APP_ADMIN);
    exit;
}

$webhookId = $_GET['webhookId'];

$ssWebhookId = $db->cell("SELECT ssWebhookId FROM webhook WHERE id = ?", $webhookId);

if ( $ssWebhookId ) {
    //delete webhook
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/webhooks/$ssWebhookId");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($webhook));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.SS_API_TOKEN, 'Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = json_decode(curl_exec($ch));
    curl_close($ch);

    // echo "<pre>";
    // print_r($response);
    // echo "</pre>";

    if ( $response->message == 'SUCCESS' ) {
        $db->delete('webhook', ['id' => $webhookId]);

        session_start();
        $_SESSION['error'] = 'Webhook deleted';

        header('Location: '.URL_APP_ADMIN.'/?page=w');
        exit;
    } else {
        session_start();
        $_SESSION['error'] = "Error. Webhook not deleted<pre>".print_r($response, true)."</pre>";

        header('Location: '.URL_APP_ADMIN.'/?page=w');
        exit;
    }
}