<?php
// --- Google Gemini API ke liye PHP Proxy ---

// CORS Headers (Cross-Origin Resource Sharing) ko aagya dein
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// Browser se aane wale OPTIONS request ko handle karein
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

// Response ka type JSON set karein
header('Content-Type: application/json');

// --- STEP 1: Apni Asli API Key Yahan Daalein ---
$apiKey = "AIzaSyDOkfpz5pHVhK4DqVtNN40A8s98deVIWYQ"; //

// Sirf POST requests ko hi aage badhne dein
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => ['message' => 'Galat request method. Sirf POST ka istemal karein.']]);
    exit;
}

// Client se data padhein
$input = json_decode(file_get_contents('php://input'), true);
$prompt = $input['prompt'] ?? null;

if (!$prompt) {
    http_response_code(400);
    echo json_encode(['error' => ['message' => 'Prompt zaroori hai.']]);
    exit;
}

// --- **DEBUGGING SECTION** ---
// Hum Google se mile response ko check karenge.
// Isse pata chalega ki API key sahi hai ya nahi.

// Google Gemini API ka URL taiyaar karein
$googleApiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=' . $apiKey;

$postData = [
    'contents' => [['parts' => [['text' => $prompt]]]]
];

$ch = curl_init($googleApiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

// Agar cURL mein hi error aa gaya
if ($curl_error) {
    http_response_code(500);
    echo json_encode(['error' => ['message' => 'cURL Error: ' . $curl_error]]);
    exit;
}

// Agar Google ne error bheja (jaise 400, 403, 404)
if ($httpcode >= 400) {
    // Hum Google ke error ko seedha display karenge
    http_response_code($httpcode);
    echo $response; // Yeh Google ka asli error message hai
    exit;
}

// Agar sab kuch sahi hai
http_response_code($httpcode);
echo $response;

?>

