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

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

$projectId = $_GET['projectId'];
$project   = $db->row("SELECT * FROM project WHERE id = ?", $projectId);
if ( !$project ) {
    session_start();
    $_SESSION['error'] = "ERROR. Webhook not created: no project with that ID";

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

$webhook = [
    "callbackUrl"   => URL_BASE.'/webhook/subscribe.php',
    "events"        => [ "*.*" ],
    'name'          => $project['title'],
    "scope"         => "sheet",
    "scopeObjectId" => $project['sheetId'],
    "version"       => 1,
];

//create webhook
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/webhooks");
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,
        'projectId'   => $project['id'],
        'name'        => $project['title'],
        'status'      => $response->result->status,
        'createdAt'   => $response->result->createdAt,
        'updatedAt'   => $response->result->modifiedAt,
    ];
    $db->insert('webhook', $webhook);

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

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

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