<?php

$datetime = date("Y-m-d H:i:s");
$txt  = "\n$datetime - ".$_SERVER['PHP_SELF']."\n";
$txt .= print_r($user, true);
$txt .= print_r($_POST, true);
$txt .= print_r($_FILES, true);

//make sure user is admin
if ( !$user['admin'] ) {
$txt .= "403 not admin\n";

    http_response_code(403);
    echo json_encode('You do not have permission to post to this project');
    exit;
}

//validate project id
if ( !$project = $db->row("SELECT * FROM project WHERE id = ?", $_POST['projectId']) ) {
$txt .= "400 invalid project\n";

    http_response_code(400);
    echo json_encode('Invalid project ID');
    exit;
} else {
$txt .= print_r($project, true);
}

//validate text and files
if ( !$text = $_POST['text'] ) {
$txt .= "400 no text\n";

    http_response_code(400);
    echo json_encode('All posts must contain text');
    exit;
}

//make sure user exists in smartsheet
if ( !$user['ssEmail'] ) {
$txt .= "403 no ssEmail\n";

    http_response_code(403);
    echo json_encode('You must be registered in Smartsheet to post updates');
    exit;
}

$whitelist = [
    'jpg',
    'JPG',
    'jpeg',
    'JPEG',
    'png',
    'PNG',
    'pdf',
    'PDF',
    'heic',
    'HEIC',
    'heif',
    'HEIF',
];

//get row id of daily log row for that project (sheet id)
$sheetId = $project['sheetId'];
$txt .= "sheetId: $sheetId\n";

if ( !$rowId = $db->cell("SELECT rowId FROM task WHERE title LIKE '%daily log%' AND projectId = ?", $project['id']) ) {
$txt .= "no rowId; getting from Smartsheet\n";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/sheets/$sheetId");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.SS_API_TOKEN, 'Content-Type: application/json', 'Assume-User: '.$user['ssEmail']]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    if ( $sheet->errorCode == 1006 || $sheet->message == 'Not Found' ) {
$txt .= "error getting sheet:\n";
$txt .= print_r($sheet, true);
        http_response_code(403);
        echo json_encode('You do not have permission to post to this project');
        exit;
    }

    //find Primary Column
    foreach ( $sheet->columns as $column ) {
        if ( $column->title == 'Primary Column' ) {
            $colId = $column->id;
$txt .= "found Primary Column ID: $colId\n";
            break;
        }
    }

    //find rowId of Daily Log row
    foreach ( $sheet->rows as $row ) {
        foreach ( $row->cells as $cell ) {
            if ( strtolower($cell->value) == 'daily log'  ) {
                $rowId = $row->id;
$txt .= "found Daily Log row ID: $rowId\n";
                break;
            }
        }
    }
}

$discussion = '{"comment": {"text": "'.$text.'"}}';
$txt .= "creating discussion: $discussion\n";

//create new discussion on row using row id (impersonate header)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/sheets/$sheetId/rows/$rowId/discussions");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer '.SS_API_TOKEN, 
    'Content-Type: application/json', 
    'Assume-User: '.$user['ssEmail'],
]);
// curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.SS_API_TOKEN, 'Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $discussion);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = json_decode(curl_exec($ch));
curl_close($ch);
$txt .= "create discussion response:\n";
$txt .= print_r($response, true);

// echo "<pre>create discussion:";
// print_r($response);
// echo "</pre>";

if ( $response->errorCode == 1006 || $response->message == 'Not Found' ) {
$txt .= "error creating discussion:\n";
$txt .= print_r($response, true);
    http_response_code(403);
    echo json_encode('You do not have permission to post to this project');
    exit;
}

$commentId = $response->result->comments[0]->id;
$txt .= "created discussion with comment: $commentId\n";

if ( !empty($_FILES) ) {
$txt .= "looping over _FILES\n";
    $files = [];
    $numFiles = count($_FILES['file']['name']);
$txt .= "numFiles: $numFiles\n";
    for ( $i = 0; $i < $numFiles; $i++ ) {
        $ext = explode('.', $_FILES['file']['name'][$i])[1];
$txt .= "$i. ".$_FILES['file']['name'][$i]."\n";
        if ( !in_array($ext, $whitelist) ) {
$txt .= "ext not in whitelist. ext: $ext\n";
            continue;
        } else {
$txt .= "adding file to list\n";
            $files[$i]['tmp_name'] = $_FILES['file']['tmp_name'][$i];
            $files[$i]['type'] = $_FILES['file']['type'][$i];
            $files[$i]['name'] = $_FILES['file']['name'][$i];
        }
    }
    
    foreach ( $files as $file ) {
$txt .= "looping over files\n";
        $upload = file_get_contents($file['tmp_name']);
    
        //attach file to comment we just created
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.smartsheet.com/2.0/sheets/$sheetId/comments/$commentId/attachments");
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.SS_API_TOKEN, 'Content-Type: '.$file['type'], 'Content-Disposition: attachment; filename="'.$file['name'].'"', 'Assume-User: '.$user['ssEmail']]);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.SS_API_TOKEN, 'Content-Type: '.$file['type'], 'Content-Disposition: attachment; filename="'.$file['name'].'"']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $upload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        $response = json_decode(curl_exec($ch));
        curl_close($ch);
$txt .= "attach file to comment response:\n";
$txt .= print_r($response, true);
    
        // echo "<pre>attach to discussion:";
        // print_r($response);
        // echo "</pre>";
    }
}
$txt .= "done\n\n\n\n";

$file = fopen(PATH_LOGS.'/btb.create-post.log', "a");
fwrite($file, $txt);
fclose($file);

http_response_code(200);
exit;