<?php

if ( !$user['superAdmin'] ) {
    http_response_code(403);
    exit;
}

//list webhooks
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/webhooks");
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->data ) {
    http_response_code(200); //return success even though we didn't find any webhooks
    exit;
}

foreach ( $response->data as $webhook ) {
    if ( !$portalOwnsWebhook = $db->row("SELECT * FROM project WHERE sheetId = ?", $webhook->scopeObjectId) ) {
        continue;
    }

    $wh = [
        'ssWebhookId' => $webhook->id,
        'sheetId'     => $webhook->scopeObjectId,
        'projectId'   => $db->cell("SELECT id FROM project WHERE sheetId = ? AND title = ?", $webhook->scopeObjectId, $webhook->name),
        'name'        => $webhook->name,
        'status'      => $webhook->status,
        'createdAt'   => $webhook->createdAt,
        'updatedAt'   => $webhook->modifiedAt
    ];

    if ( $exists = $db->cell("SELECT id FROM webhook WHERE ssWebhookId = ?", $wh['ssWebhookId']) ) {
        $db->update('webhook', $wh, ['ssWebhookId' => $webhook->id]);
    } else {
        $db->insert('webhook', $wh);
    }
}

$webhooks = $db->run("SELECT * FROM webhook");

// $template = ( $user['email'] === 'lambo117@gmail.com' )
//     ? 'webhooks-table-test.php'
//     : 'webhooks-table.php'
// ;
// include "../template/$template";
include '../template/webhooks-table-test.php';