<?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 ) {
    session_start();
    $_SESSION['error'] = "ERROR. Webhook not verified: no webhook with that ID";

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

$webhook = [
    "enabled" => true
];

//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' ) {
    $webhook = [
        'ssWebhookId' => $response->result->id,
        '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 verified';

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

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