<?php

if ( !$user['admin'] ) {
    header("Location: https://bigtimberbuilders.com/clients/dashboard");
    exit;
}

$projects = $db->run("SELECT * FROM project");

foreach ( $projects as $project ) {
    $i     = 0;
    $tasks = [];

    $sheetId = $project['sheetId'];

    //get job sheet
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/sheets/$sheetId");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer qJc6jnLsHoqznwCbkApNwLMQamt6ITcykpgen", 'Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $sheet = json_decode(curl_exec($ch));
    curl_close($ch);

    echo "<pre>";
    print_r($sheet);
    echo "</pre>";

    foreach ( $sheet->columns as $column ) {
        if ( $column->title == 'Primary Column' ) {
            $titleColumnId = $column->id;
            continue;
        }
        if ( $column->title == 'Status' ) {
            $statusColumnId = $column->id;
            continue;
        }
    }

    $rootFound = false;
    $k = 0;
    foreach ( $sheet->rows as $row ) {
        foreach ( $row->cells as $cell ) {
            if ( !$rootFound ) {
                if ( str_contains(strtolower($cell->value), 'task list') ) {
                    $root = $row->id;
                    $rootFound = true;
                }
            }
            if ( $cell->columnId == $titleColumnId ) {
                $tasks[$k]['rowId']     = $row->id;
                $tasks[$k]['parentId']  = $row->parentId;
                $tasks[$k]['projectId'] = "REPLACE";
                $tasks[$k]['title']     = $cell->value;
                $tasks[$k]['row']       = $row->number;
                continue;
            }
            if ( $cell->columnId == $statusColumnId ) {
                $tasks[$k]['rowId']    = $row->id;
                $tasks[$k]['parentId'] = $row->parentId;
                $tasks[$k]['projectId'] = "REPLACE";
                $tasks[$k]['status']   = $cell->value;
                $tasks[$k]['row']      = $row->number;
                continue;
            }
        }
        $k++;
    }
    $i++;
    echo "<pre>";
    print_r($tasks);
    echo "</pre>";

    foreach ( $tasks as $task ) {
        if ( $task['parentId'] == $root ) {
?>
            <h1><?php echo $task['title'] ?></h1>
<?php
        } else {
?>
            <p><?php echo $task['title'] ?> / <?php echo $task['status'] ?></p>
<?php
        }
    }

exit;
}
