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

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

$title = trim($_POST['title']);
if ( !$title ) {
    session_start();
    $_SESSION['error'] = 'Title cannot be blank';

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

if ( $db->cell("SELECT title FROM project WHERE title = ?", $title) ) {
    session_start();
    $_SESSION['error'] = 'A project with that title already exists';

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

$status = trim($_POST['status']);
if ( !$status ) {
    $status = 'Active';
}

$sheetId = trim($_POST['sheetId']);
if ( !$sheetId ) {
    session_start();
    $_SESSION['error'] = 'Sheet ID cannot be blank';

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

$zip = trim($_POST['zip']);
if ( !$zip ) {
    session_start();
    $_SESSION['error'] = 'ZIP cannot be blank';

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

if ( strlen($zip) != 5 ) {
    session_start();
    $_SESSION['error'] = 'ZIP must be 5 characters';

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

$city = trim($_POST['city']);
if ( !$city ) {
    session_start();
    $_SESSION['error'] = 'City cannot be blank';

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

$error = '';

$projectInsert = [
    'title'   => $title,
    'status'  => $status,
    'sheetId' => $sheetId,
    'zip'     => $zip,
    'city'    => $city,
];
$projectInsert['createdBy'] = $user['id'];
$projectInsert['createdAt'] = date('Y-m-d H:i:s');

$db->insert('project', $projectInsert);

$project = $db->row("SELECT * FROM project WHERE title = ? AND status = ? AND sheetId = ? AND zip = ? AND city = ? AND createdBy = ? AND createdAt = ?", 
    $projectInsert['title'],
    $projectInsert['status'],
    $projectInsert['sheetId'],
    $projectInsert['zip'],
    $projectInsert['city'],
    $projectInsert['createdBy'],
    $projectInsert['createdAt'],
);

if ( $_POST['addClientProject'] ) {
    $ids = $_POST['clients'];
    foreach ( $ids as $id ) {
        $db->insert('client_project', ['clientId' => $id, 'projectId' => $project['id']]);
    }
}

$error .= "Project created<br>";

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

$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);

    $error .= "Webhook created<br>";
} else {
    $error .= 'ERROR. Webhook not created: <pre>'.print_r($response, true).'</pre>';
}

//verify webhook
$ssWebhookId = $webhook['ssWebhookId'];
$webhookId   = $db->cell("SELECT id FROM webhook WHERE ssWebhookId = ?", $ssWebhookId);
$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]);

    $error .= "Webhook verified<br>";
} else {
    $error .= "ERROR. Webhook not verfied: <pre>".print_r($response, true)."</pre>";
}

//include fetch

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

header('Location: '.URL_APP_ADMIN.'/?page=p');
exit;
?>