Files
musadaq-saas/app/Modules/AI/AIController.php

84 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\AI;
use App\Core\{Request, Response, Database};
use GuzzleHttp\Client;
use Throwable;
final class AIController
{
private Client $httpClient;
private string $apiKey;
private string $model;
public function __construct()
{
$this->httpClient = new Client();
$this->apiKey = $_ENV['GEMINI_API_KEY'] ?? '';
$this->model = $_ENV['GEMINI_MODEL'] ?? 'gemini-2.0-flash';
}
public function query(Request $request): void
{
$userQuery = $request->input('query');
if (!$userQuery) {
Response::error('يرجى تقديم استفسار', 'MISSING_QUERY', 422);
return;
}
try {
// 1. Fetch current context data (Summary of stats)
$stats = $this->getQuickStats($request->tenantId);
// 2. Ask Gemini to interpret and answer
$prompt = "You are Musadaq AI Assistant for a Jordanian E-Invoicing SaaS. " .
"The user is asking: \"{$userQuery}\". " .
"Current User Context: Tenant ID {$request->tenantId}. " .
"Current Data Summary: " . json_encode($stats) . ". " .
"Answer the user in a friendly Arabic tone (Jordanian dialect is okay). " .
"Keep it professional and concise. If you don't have the specific data, say so politely.";
$response = $this->httpClient->post("https://generativelanguage.googleapis.com/v1beta/models/{$this->model}:generateContent?key={$this->apiKey}", [
'json' => [
'contents' => [['parts' => [['text' => $prompt]]]]
]
]);
$data = json_decode($response->getBody()->getContents(), true);
$answer = $data['candidates'][0]['content']['parts'][0]['text'] ?? 'عذراً، لم أستطع فهم الاستفسار حالياً.';
Response::json([
'success' => true,
'data' => [
'answer' => $answer
]
]);
} catch (Throwable $e) {
Response::error('فشل معالجة الاستعلام الذكي', 'AI_QUERY_FAILED', 500, [
'error' => $e->getMessage()
]);
}
}
private function getQuickStats(string $tenantId): array
{
$db = Database::getInstance();
$totalInvoices = $db->prepare("SELECT COUNT(*) as total FROM invoices WHERE tenant_id = ?");
$totalInvoices->execute([$tenantId]);
$approvedCount = $db->prepare("SELECT COUNT(*) as total FROM invoices WHERE tenant_id = ? AND status = 'approved'");
$approvedCount->execute([$tenantId]);
return [
'total_invoices' => $totalInvoices->fetch()['total'],
'approved_invoices' => $approvedCount->fetch()['total'],
'current_month' => date('F Y')
];
}
}