false, 'error' => $message]); exit; } // 1. Handle File Upload if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) { return_error('File upload error. Please try again. Code: ' . ($_FILES['csv_file']['error'] ?? 'Unknown')); } $file = $_FILES['csv_file']; $tmpPath = $file['tmp_name']; // 2. Validate File Type (Basic Check) $fileType = mime_content_type($tmpPath); $fileName = $file['name']; $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if ($fileType !== 'text/csv' && $fileType !== 'text/plain' && $fileExtension !== 'csv') { return_error('Invalid file type. Please upload a valid CSV file.'); } // 3. Move Uploaded File to a Permanent Location $uploadsDir = __DIR__ . '/uploads/'; if (!is_dir($uploadsDir)) { mkdir($uploadsDir, 0777, true); } $safeFileName = preg_replace("/[^a-zA-Z0-9_.-]|\.\.+/", "", basename($fileName)); $newFilePath = $uploadsDir . uniqid() . '-' . $safeFileName; if (!move_uploaded_file($tmpPath, $newFilePath)) { return_error('Failed to save the uploaded file.'); } // 4. Read CSV Header and First 2 Rows from the new path $dataSample = ''; $handle = fopen($newFilePath, 'r'); if (!$handle) { return_error('Failed to open the uploaded file.'); } $lineCount = 0; while (($row = fgetcsv($handle)) !== false && $lineCount < 3) { $dataSample .= implode(',', array_map(function($cell) { return '"' . addslashes($cell) . '"'; }, $row)) . "\n"; $lineCount++; } fclose($handle); if (empty($dataSample)) { return_error('The CSV file appears to be empty or could not be read.'); } // 4. Prepare Prompt for AI $prompt = <<` and `
  • ` tags. 3. **Suggest Key Statistics:** In a bulleted list, suggest 2-3 key statistical calculations (e.g., average, sum, distribution) that would be meaningful for this dataset. Use `