<?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 ) {
    $webhook = [
        //     "callbackUrl"   => URL_BASE.'/webhook/subscribe.php',
                "enabled"    => false,
        //     "events"        => [ "*.*" ],
        //     'name'          => 'BTB Subscriber',
        //     "scope"         => "sheet",
        //     "scopeObjectId" => $sheetId,
        //     "version"       => 1,
        ];
        
        //update webhook
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/webhooks/$ssWebhookId");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        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]);
            $webhook = [
                'ssWebhookId' => $response->result->id,
                'sheetId'     => $response->result->scopeObjectId,
                'projectId'   => $db->cell("SELECT id FROM project WHERE sheetId = ?", $response->result->scopeObjectId),
                'name'        => $db->cell("SELECT title FROM project WHERE sheetId = ?", $response->result->scopeObjectId),
                'status'      => $response->result->status,
                'createdAt'   => $response->result->createdAt,
                'updatedAt'   => $response->result->modifiedAt,
            ];
            $db->update('webhook', $webhook, ['id' => $webhookId]);
        
            session_start();
            $_SESSION['error'] = "Webhook disabled<pre>".print_r($response, true)."</pre>";
    
            header('Location: '.URL_APP_ADMIN.'/?page=w');
            exit;
        } else {
            session_start();
            $_SESSION['error'] = "Error. Webhook not disabled<pre>".print_r($response, true)."</pre>";
    
            header('Location: '.URL_APP_ADMIN.'/?page=w');
            exit;
        }
}
