<?php

$parentFolderId = SS_TASK_LIST_FOLDER; // "/BTB Client Workspace/BTB Client Folders"

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/folders/$parentFolderId");
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>";

$folders = $response->folders;

$i      = 0;
$sheets = [];
foreach ( $folders as $folder ) {
    $folderId = $folder->id;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/folders/$folderId");
    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>";

    $sheetsInFolder = $response->sheets;
    foreach ( $sheetsInFolder as $sheet ) {
        if ( (str_contains(strtolower($sheet->name), 'task list') || str_contains(strtolower($sheet->name), 'selections') ) && !str_contains(strtolower($sheet->name), 'template') ) {
            $sheets[$i]['id']   = $sheet->id;
            $sheets[$i]['name'] = $sheet->name;
            // $sheets[$i]['name'] = str_ireplace(' build task list', '', $sheets[$i]['name']);
            // $sheets[$i]['name'] = str_ireplace(' task list', '', $sheets[$i]['name']);

            $i++;
        }
    }
}
?>
    <option value="">Select a sheet</option>
<?php
    foreach ( $sheets as $sheet ) {
?>
        <option value="<?php echo $sheet['id']; ?>"><?php echo $sheet['name']; ?></option>
<?php
    }

    $sheets[$i]['name'] = str_replace('Build Task List', '', $sheet[$i]['name']);