prepare("SELECT credits FROM users WHERE id = ?"); $stmt->execute([$_SESSION['user_id']]); $user = $stmt->fetch(); if (!$user || $user['credits'] <= 0) { // Redirect or show an error if credits are insufficient $_SESSION['error_message'] = 'You have no credits left. Please purchase more to continue.'; header('Location: pricing.php'); exit(); } if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_id'])) { $uploadId = $_POST['upload_id']; $userId = $_SESSION['user_id']; // Re-verify the upload belongs to the user $stmt = $pdo->prepare("SELECT * FROM uploads WHERE id = ? AND user_id = ?"); $stmt->execute([$uploadId, $userId]); $upload = $stmt->fetch(); if ($upload) { // Deduct one credit BEFORE starting the analysis $pdo->prepare("UPDATE users SET credits = credits - 1 WHERE id = ?")->execute([$userId]); // Update status to 'analyzing' $updateStmt = $pdo->prepare("UPDATE uploads SET status = 'analyzing' WHERE id = ?"); $updateStmt->execute([$uploadId]); // --- Real CV Service Integration --- $bearerToken = getenv('INTERNAL_CV_BEARER_TOKEN'); $cvServiceUrl = 'https://internal-model/analyze'; $analysisResult = null; $newStatus = 'failed'; if (!$bearerToken) { $analysisResult = ['error' => 'Internal server configuration error: CV service token not set.']; } elseif (empty($upload['file_path']) || !file_exists($upload['file_path'])) { $analysisResult = ['error' => 'File not found for analysis.']; } else { // Prepare cURL request $ch = curl_init(); $cfile = new CURLFile($upload['file_path'], mime_content_type($upload['file_path']), basename($upload['file_path'])); curl_setopt($ch, CURLOPT_URL, $cvServiceUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $cfile]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $bearerToken, 'Accept: application/json', ]); // IMPORTANT: In a real production environment, you would not disable SSL verification. // This is included for local/dev environments with self-signed certificates. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($curlError) { $analysisResult = ['error' => 'cURL Error: ' . $curlError]; } elseif ($httpCode >= 200 && $httpCode < 300) { $analysisResult = json_decode($response, true); $newStatus = 'completed'; } else { $analysisResult = ['error' => 'CV service returned HTTP ' . $httpCode, 'response' => $response]; } } // Store the result and update status $resultStmt = $pdo->prepare("UPDATE uploads SET status = ?, analysis_result = ? WHERE id = ?"); $resultStmt->execute([$newStatus, json_encode($analysisResult), $uploadId]); } } header('Location: index.php'); exit(); ?>