<?php
// socialmediamanager/app/openai.php
require_once __DIR__ . "/db.php";

function smm_openai_enabled(): bool {
  $cfg = smm_config();
  return isset($cfg["openai_api_key"]) && trim($cfg["openai_api_key"]) !== "";
}

function smm_openai_chat(array $messages, array $opts=[]): array {
  $cfg = smm_config();
  $apiKey = $cfg["openai_api_key"] ?? "";
  if (trim($apiKey) === "") throw new Exception("OpenAI API key not set in app/config.php");

  $model = $opts["model"] ?? ($cfg["openai_model"] ?? "gpt-4o-mini");
  $temperature = $opts["temperature"] ?? 0.7;

  $payload = ["model"=>$model,"messages"=>$messages,"temperature"=>$temperature];

  $ch = curl_init("https://api.openai.com/v1/chat/completions");
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_POST=>true,
    CURLOPT_HTTPHEADER=>[
      "Authorization: Bearer ".$apiKey,
      "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS=>json_encode($payload),
    CURLOPT_TIMEOUT=>60,
  ]);
  $resp = curl_exec($ch);
  $err = curl_error($ch);
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($resp === false) throw new Exception("cURL error: ".$err);
  $data = json_decode($resp, true);
  if ($status < 200 || $status >= 300) {
    $msg = $data["error"]["message"] ?? $resp;
    throw new Exception("OpenAI error ($status): ".$msg);
  }
  return $data;
}
