<?php
// Function to manually get MIME type based on file extension
function getMimeType($filePath) {
    $extension = pathinfo($filePath, PATHINFO_EXTENSION);
    switch ($extension) {
        case 'xlsx':
            return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        case 'xls':
            return 'application/vnd.ms-excel';
        default:
            return 'application/octet-stream'; // Fallback for unknown file types
    }
}

// Logging function
function logMessage($message) {
    $file = fopen('debug.txt', 'a');
    fwrite($file, date('Y-m-d H:i:s') . ' - ' . $message . "\n");
    fclose($file);
}

logMessage("Starting script...");

// Get the username, serialNo, itemNo, description, and popRealname from POST data
$username = $_POST['username'];
$serialNo = $_POST['serialNo'];
$popRealname = $_POST['popRealname'] ?? 'null'; // Ensure non-null value
$itemNo = $_POST['itemNo'];
$description = $_POST['description'];

logMessage("Received data - Username: $username, SerialNo: $serialNo, ItemNo: $itemNo, Description: $description, RealName: $popRealname");

// Define static file path for testing
$filePath = $_FILES['file']['tmp_name'];  // Temporary location of uploaded file
$uploadDir = __DIR__ . '/temp/';  // Ensure this directory exists and is writable
$destinationPath = '/home/servicelabotek/public_html/serviceplatform/temp/' . basename($_FILES['file']['name']);  // Destination path

if (!copy($filePath, $destinationPath)) {
    logMessage("Failed to copy file to temp directory.");
    echo json_encode(['status_code' => 500, 'error_message' => 'Failed to copy file to temp directory.']);
    exit;
}
logMessage("File copied to temp directory at: $destinationPath");

// Monday.com API URL
$apiUrl = "https://api.monday.com/v2";

// API Key
$apiKey = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjI5NjkzOTQ5OSwiYWFpIjoxMSwidWlkIjoyODU3NTM3MCwiaWFkIjoiMjAyMy0xMS0xN1QxMToyNjoyMy4wOTZaIiwicGVyIjoibWU6d3JpdGUiLCJhY3RpZCI6ODk5NjkyLCJyZ24iOiJ1c2UxIn0.QG7I33YsXwPrFACmKW6exmJrzqH2jmrbcmmoG38bs48';

// Board ID
$boardId = '5601232227'; // Your specific board ID for orders

// Prepare the column values as a JSON object
$columnValues = json_encode([
    'text2__1' => $serialNo,
    'text5__1' => $username,
    'text4__1' => $itemNo,
    'text44__1' => $description,
    'text0__1' => $_POST['name'], // Name field
    'email__1' => [
        'email' => $_POST['email'],
        'text' => $_POST['name']
    ]
]);


// Create a new item on Monday.com with additional column values
$queryCreateItem = '
mutation {
    create_item (board_id: ' . $boardId . ', item_name: "' . $popRealname . '", column_values: "' . addslashes($columnValues) . '") {
        id
    }
}';

$headers = [
    'Authorization: ' . $apiKey,
    'Content-Type: application/json',
];

logMessage("Create Item Query: " . $queryCreateItem);
logMessage("Headers: " . json_encode($headers));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['query' => $queryCreateItem]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

logMessage("Create Item cURL HTTP Status: " . $httpStatus);
logMessage("Create Item cURL Error: " . $curlError);
logMessage("Create Item Response: " . $result);

$responseData = json_decode($result, true);

if ($httpStatus !== 200 || isset($responseData['errors'])) {
    logMessage("Failed to create item: " . $result);
    echo json_encode(['status_code' => 500, 'error_message' => 'Failed to create item.']);
    exit;
}

logMessage("File details: " . json_encode($_FILES));

$itemId = $responseData['data']['create_item']['id'];
$columnId = 'files__1'; // Correct column ID for file uploads
logMessage("Created Item ID: " . $itemId);

// Proceed to file upload
logMessage("Proceeding to file upload step");

// Public File Path for Monday.com (For verification purposes)
$publicFilePath = 'https://service.labotek.dk/serviceplatform/temp/' . basename($destinationPath);
logMessage("Public File Path (for download): $publicFilePath");

// Prepare the file data using curl_file_create for file upload
$file = curl_file_create($destinationPath, getMimeType($destinationPath), basename($destinationPath));

// Prepare the file data for Monday.com file upload
$body = [
    'query' => 'mutation ($file: File!) { add_file_to_column (item_id: ' . $itemId . ', column_id: "' . $columnId . '", file: $file) { id } }',
    'variables[file]' => $file
];

$headers = [
    'Authorization: ' . $apiKey,
    'Content-Type: ' . 'multipart/form-data',
];

// Send the cURL request with the multipart/form-data body
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

logMessage("File Upload cURL HTTP Status: " . $httpStatus);
logMessage("File Upload cURL Error: " . $curlError);
logMessage("Received response from file upload: " . $response);

$responseData = json_decode($response, true);

if ($httpStatus === 200 && isset($responseData['data']['add_file_to_column']['id'])) {
    logMessage("File uploaded successfully: " . $responseData['data']['add_file_to_column']['id']);
    echo json_encode(['status_code' => 200, 'message' => 'Success']);
} else {
    logMessage("Failed to upload file: " . $response);
    echo json_encode(['status_code' => 500, 'error_message' => 'Failed to upload file.']);
}

logMessage("Script ended.");
?>
