<?php
/**
 * AstroNirnay Developer API client for PHP 7.4+ (needs the curl and json extensions). No other dependencies.
 * Generated from https://api.astronirnay.com/v1/openapi.json, so it always matches the live API.
 *
 *   require "astronirnay.php";
 *   $client = new AstroNirnay\Client("YOUR_API_KEY");
 *   $chart = $client->chart(["birth" => ["date" => "1990-05-15", "time" => "10:30",
 *       "latitude" => 19.076, "longitude" => 72.8777, "timezone" => "Asia/Kolkata"]]);
 *   echo $chart["ascendant"]["sign"], " ", $client->creditsRemaining;
 *
 * Time is 24-hour (HH:MM). Keep your key on the server, never in a browser or app.
 */
namespace AstroNirnay;

class ApiException extends \Exception
{
    /** @var int */ public $status;
    /** @var string */ public $errorCode;
    /** @var array */ public $details;
    /** @var string|null */ public $requestId;

    public function __construct(int $status, string $errorCode, string $message, array $details = [], ?string $requestId = null)
    {
        parent::__construct("[$status] $errorCode: $message", $status);
        $this->status = $status;
        $this->errorCode = $errorCode;
        $this->details = $details;
        $this->requestId = $requestId;
    }
}

class Client
{
    const DEFAULT_BASE_URL = 'https://api.astronirnay.com/v1';

    private $apiKey;
    private $baseUrl;
    private $timeout;
    private $maxRetries;
    /** @var int|null Credits left, from the X-Credits-Remaining header of the last call. */
    public $creditsRemaining = null;
    /** @var string|null */
    public $lastRequestId = null;

    public function __construct(string $apiKey, array $options = [])
    {
        if ($apiKey === '') {
            throw new \InvalidArgumentException('apiKey is required');
        }
        $this->apiKey = $apiKey;
        $this->baseUrl = rtrim($options['baseUrl'] ?? self::DEFAULT_BASE_URL, '/');
        $this->timeout = $options['timeout'] ?? 30;
        $this->maxRetries = $options['maxRetries'] ?? 3;
    }

    private function request(string $method, string $path, ?array $body = null, array $query = [], bool $secured = true)
    {
        $url = $this->baseUrl . $path;
        $query = array_filter($query, function ($v) { return $v !== null; });
        if ($query) {
            $url .= '?' . http_build_query($query);
        }
        $headers = ['Accept: application/json', 'User-Agent: astronirnay-php/1.0'];
        $payload = null;
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            $payload = json_encode($body);
        }
        if ($secured) {
            $headers[] = 'x-api-key: ' . $this->apiKey;
        }
        for ($attempt = 0; ; $attempt++) {
            $respHeaders = [];
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_CUSTOMREQUEST => $method,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => $this->timeout,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_HEADERFUNCTION => function ($c, $line) use (&$respHeaders) {
                    $parts = explode(':', $line, 2);
                    if (count($parts) === 2) {
                        $respHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
                    }
                    return strlen($line);
                },
            ]);
            if ($payload !== null) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            }
            $text = curl_exec($ch);
            $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlError = curl_error($ch);
            if (PHP_VERSION_ID < 80000) {
                curl_close($ch);
            }
            if ($text === false) {
                throw new ApiException(0, 'network_error', $curlError ?: 'Network error');
            }
            if (in_array($status, [429, 502, 503, 504], true) && $attempt < $this->maxRetries) {
                $wait = isset($respHeaders['retry-after']) && is_numeric($respHeaders['retry-after']) ? (float) $respHeaders['retry-after'] : min(pow(2, $attempt + 1), 8);
                usleep((int) ($wait * 1000000));
                continue;
            }
            if (isset($respHeaders['x-credits-remaining']) && is_numeric($respHeaders['x-credits-remaining'])) {
                $this->creditsRemaining = (int) $respHeaders['x-credits-remaining'];
            }
            if (strpos($respHeaders['content-type'] ?? '', 'json') === false) {
                if ($status >= 400) {
                    throw new ApiException($status, 'http_error', substr($text, 0, 200));
                }
                return $text;
            }
            $data = json_decode($text, true);
            if (!is_array($data)) {
                throw new ApiException($status, 'bad_response', 'The server did not return valid JSON');
            }
            $this->lastRequestId = $data['meta']['request_id'] ?? null;
            if ($status >= 400 || empty($data['success'])) {
                $err = $data['error'] ?? [];
                throw new ApiException($status, $err['code'] ?? 'error', $err['message'] ?? 'Request failed', $err['details'] ?? [], $this->lastRequestId);
            }
            return $data['data'] ?? null;
        }
    }

    /**
     * Complete birth chart.
     * POST /v1/chart
     * Ascendant, all nine planets with sign, degree, nakshatra, pada, dignity, retrograde and combustion flags, the twelve houses, and optional divisional charts (`divisions`: D1, D2, D3, D4, D6, D7, D9, D10, D12, D16, D20, D24, D27, D30, D40, D45, D60).
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function chart(array $body)
    {
        return $this->request('POST', '/chart', $body, [], true);
    }

    /**
     * Planet positions.
     * POST /v1/planets
     * Sidereal positions of the Sun, Moon, Mars, Mercury, Jupiter, Venus, Saturn, Rahu and Ketu.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function planets(array $body)
    {
        return $this->request('POST', '/planets', $body, [], true);
    }

    /**
     * Houses and occupants.
     * POST /v1/houses
     * Twelve houses under `whole_sign` (default) or `equal_house`, with the planets in each.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function houses(array $body)
    {
        return $this->request('POST', '/houses', $body, [], true);
    }

    /**
     * Vimshottari dasha.
     * POST /v1/dasha/vimshottari
     * Balance at birth, the running mahadasha → prana chain at `at` (up to `depth` levels, default 3, max 5) and the nested period timeline (`periods_depth` 0–3, default 2) for up to 120 years.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function dashaVimshottari(array $body)
    {
        return $this->request('POST', '/dasha/vimshottari', $body, [], true);
    }

    /**
     * Daily panchang.
     * POST /v1/panchang
     * Weekday, sunrise/sunset, moonrise/moonset, tithi, nakshatra, yoga and karana with exact start and end times (as they stand at sunrise, plus every one running during the day), Rahu kaal, Yamaganda, Gulika kaal and Abhijit muhurta.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function panchang(array $body)
    {
        return $this->request('POST', '/panchang', $body, [], true);
    }

    /**
     * Sade Sati and Dhaiya.
     * POST /v1/doshas/sade-sati
     * Whether Saturn is currently over the 12th, 1st or 2nd sign from the natal Moon (sade sati) or the 4th/8th (dhaiya), the current period and cycle, the next cycle, and a lifetime timeline (`timeline_years`, default 90; set `include_timeline` false to skip it).
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function doshasSadeSati(array $body)
    {
        return $this->request('POST', '/doshas/sade-sati', $body, [], true);
    }

    /**
     * Manglik dosha.
     * POST /v1/doshas/manglik
     * Mars position from Lagna, Moon and Venus, whether the chart is Manglik, severity, the cancellation rules that apply, and the Navamsa position. The rule set is published in the response (`rules`).
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function doshasManglik(array $body)
    {
        return $this->request('POST', '/doshas/manglik', $body, [], true);
    }

    /**
     * Ashtakoot matching.
     * POST /v1/matching/ashtakoot
     * Eight koota scores (36 points), percentage, verdict band, nadi and bhakoot doshas, and manglik compatibility between a groom and a bride.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function matchingAshtakoot(array $body)
    {
        return $this->request('POST', '/matching/ashtakoot', $body, [], true);
    }

    /**
     * Chart image (SVG).
     * POST /v1/chart/image
     * The birth chart (or a divisional chart via `division`, e.g. "D9") drawn as an SVG string in North Indian (`style: "north"`, default) or South Indian (`"south"`) style, plus the houses and their planets as data.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function chartImage(array $body)
    {
        return $this->request('POST', '/chart/image', $body, [], true);
    }

    /**
     * Ashtakvarga.
     * POST /v1/ashtakvarga
     * Bhinna Ashtakvarga points for Sun to Saturn in every sign and house, and the Sarva Ashtakvarga total (337 points). Set `include_contributions` true to see which contributor gave each point.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function ashtakvarga(array $body)
    {
        return $this->request('POST', '/ashtakvarga', $body, [], true);
    }

    /**
     * Yogini dasha.
     * POST /v1/dasha/yogini
     * The 36-year Yogini dasha from the birth nakshatra: balance at birth, running chain at `at` (`depth` 1–3, default 2) and the nested timeline (`periods_depth` 0–3, default 1) for about 120 years.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function dashaYogini(array $body)
    {
        return $this->request('POST', '/dasha/yogini', $body, [], true);
    }

    /**
     * Jaimini Chara dasha.
     * POST /v1/dasha/char
     * Sign-based Chara dasha mahadashas from the Lagna (Gary Gomes / K.N. Rao convention, published in the response), with the running period at `at`. Antardashas are not included. `cycles` 1–3 (default 1).
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function dashaChar(array $body)
    {
        return $this->request('POST', '/dasha/char', $body, [], true);
    }

    /**
     * Kaal Sarp dosha.
     * POST /v1/doshas/kalsarpa
     * Whether all seven planets lie on one side of the Rahu-Ketu axis (full) or all but one (partial), the direction, and the named type from the house of Rahu. Reports the astronomical condition only.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function doshasKalsarpa(array $body)
    {
        return $this->request('POST', '/doshas/kalsarpa', $body, [], true);
    }

    /**
     * Classical yogas.
     * POST /v1/yogas
     * Which classical yogas are present in a birth chart: the five Mahapurusha yogas, Gajakesari, Budhaditya, Chandra-Mangala, Sunapha, Anapha, Durudhara, Kemadruma, Vesi, Vosi, Ubhayachari, Adhi, Amala, the three Parivartana types, Harsha, Sarala, Vimala, Guru-Chandala, the Grahana yogas, Shrapit and Angarak, plus clearly labelled variants (counted from the Moon, Jupiter with Ketu). Each yoga lists the exact conditions met, anything that weakens or modifies it, cancellations where they apply (Kemadruma), a fixed description and its source. There is no numeric score. Set include_absent to also list the yogas that were checked and are not formed.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function yogas(array $body)
    {
        return $this->request('POST', '/yogas', $body, [], true);
    }

    /**
     * Varshaphal (annual chart).
     * POST /v1/varshaphal
     * The annual chart for a year: the exact Varsha Pravesh (the instant the Sun returns to its natal sidereal longitude, in UTC and local time), the annual chart for that moment at the birth place or a place you choose, the Muntha (sign, house, lord), the five officers (Panchadhikari) with their positions, and the Mudda dasha for the year. This is Phase A: the year lord is not selected, and the Tri-rashi and Dina-ratri officers are returned as pending because authors differ and the rules await confirmation by an astrologer. The Mudda dasha year length is an input (365.25 or 360 days).
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function varshaphal(array $body)
    {
        return $this->request('POST', '/varshaphal', $body, [], true);
    }

    /**
     * Choghadiya.
     * POST /v1/muhurta/chaughadiya
     * The eight day and eight night choghadiyas (Udveg, Chal, Labh, Amrit, Kaal, Shubh, Rog) with exact times and their auspicious / neutral / inauspicious nature.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function muhurtaChaughadiya(array $body)
    {
        return $this->request('POST', '/muhurta/chaughadiya', $body, [], true);
    }

    /**
     * Hora (planetary hours).
     * POST /v1/muhurta/hora
     * The 12 day and 12 night planetary hours with the ruling planet and exact times.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function muhurtaHora(array $body)
    {
        return $this->request('POST', '/muhurta/hora', $body, [], true);
    }

    /**
     * Biorhythm.
     * POST /v1/biorhythm
     * Physical (23 day), emotional (28 day) and intellectual (33 day) cycle values from -100 to 100 for a date (and up to 62 days) from the birth date.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function biorhythm(array $body)
    {
        return $this->request('POST', '/biorhythm', $body, [], true);
    }

    /**
     * Ayanamsha value.
     * GET /v1/ayanamsha
     * The Lahiri ayanamsha for a date (default today).
     * @param array $params Query parameters: date.
     * @return mixed
     */
    public function ayanamsha(array $params = [])
    {
        return $this->request('GET', '/ayanamsha', null, $params, true);
    }

    /**
     * Planet nature table.
     * GET /v1/reference/planet-nature
     * Classical attributes of the nine planets: nature, element, friends and enemies, exaltation, own signs and more. Free.
     * @param array $params Query parameters: lang.
     * @return mixed
     */
    public function referencePlanetNature(array $params = [])
    {
        return $this->request('GET', '/reference/planet-nature', null, $params, true);
    }

    /**
     * AI prediction.
     * POST /v1/ai/prediction
     * AI-written prediction for one area of life over a day, week, month or year, in any of 21 languages (en = English, hinglish = Hinglish (Hindi in Roman script), hi = Hindi, mr = Marathi, bn = Bengali, gu = Gujarati, ta = Tamil, te = Telugu, kn = Kannada, ml = Malayalam, pa = Punjabi, or = Odia, ur = Urdu, as = Assamese, ne = Nepali, sa = Sanskrit, kok = Konkani, mai = Maithili, doi = Dogri, sd = Sindhi, ks = Kashmiri). The text is written by OpenAI strictly from facts our engine calculates (returned in facts_used: chart, running dasha, sade sati, transits). Credits depend on the language (English 15, Hindi 25, Odia 55); failed generations are refunded. Not yet available: Bodo, Manipuri (Meitei), Santali. Languages marked beta in /ai/pricing have not yet been reviewed by native speakers. Areas: general, career, finance, marriage, family, education, health. Periods: today, week, month, year.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function aiPrediction(array $body)
    {
        return $this->request('POST', '/ai/prediction', $body, [], true);
    }

    /**
     * AI ask (free-text chat Q&A).
     * POST /v1/ai/ask
     * Ask any astrology question in free text and get one conversational answer, in any of 21 languages — the same persona, safety and quality rules as the AstroNirnay app's AI chat, but stateless (no account, no chat history stored on our side; optionally pass up to 10 prior turns yourself in `history`). The answer is written by OpenAI strictly from facts our engine calculates (returned in facts_used). Messages detected as self-harm/crisis ideation never reach the model: they get a static support-helpline redirect and are never charged (credits_charged: 0). Credits depend on the language (English 15, Hindi 25, Odia 55); failed generations are refunded.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function aiAsk(array $body)
    {
        return $this->request('POST', '/ai/ask', $body, [], true);
    }

    /**
     * Create an AI report (PDF).
     * POST /v1/ai/reports
     * Starts a branded PDF report and returns 202 with a job id. Reports: sade_sati = Sade Sati report, manglik = Manglik report, roadmap_12m = 12-month roadmap, premium_kundali = Premium Personalized Kundali, career_roadmap_5yr = Career 5-Year Roadmap, wealth_roadmap_5yr = Wealth 5-Year Roadmap, love_roadmap_5yr = Love 5-Year Roadmap, marriage_roadmap_5yr = Marriage 5-Year Roadmap, health_roadmap_5yr = Health 5-Year Roadmap, business_roadmap_5yr = Business 5-Year Roadmap. Languages: en, hi, mr, ta, te (more are added after native-speaker review). Credits are charged now (sade_sati 45 in English, manglik 45 in English, roadmap_12m 60 in English, premium_kundali 155 in English, career_roadmap_5yr 40 in English, wealth_roadmap_5yr 40 in English, love_roadmap_5yr 40 in English, marriage_roadmap_5yr 40 in English, health_roadmap_5yr 40 in English, business_roadmap_5yr 40 in English; other languages cost more) and refunded automatically if the report fails. Poll GET /ai/reports/{id} until status is done (typically 30-90 seconds), then download the PDF. The PDF carries the logo and company name you saved under Branding in the dashboard. subject_name is printed on the PDF only and is never sent to the AI. Reports are kept for 30 days. At most 3 reports can be generating at once.
     * @param array $body Request body (see the example in the docs).
     * @return mixed
     */
    public function aiReports(array $body)
    {
        return $this->request('POST', '/ai/reports', $body, [], true);
    }

    /**
     * List your recent reports.
     * GET /v1/ai/reports
     * Your 20 most recent reports with status and download links. Free.
     * @param array $params Query parameters: lang.
     * @return mixed
     */
    public function aiReports(array $params = [])
    {
        return $this->request('GET', '/ai/reports', null, $params, true);
    }

    /**
     * Report status and content.
     * GET /v1/ai/reports/{id}
     * Status (queued, running, done, failed), progress, and when done the report sections as JSON, the facts used, and the pdf_url. A failed report is refunded (refunded: true). Free.
     * @param array $params Query parameters: lang.
     * @return mixed
     */
    public function aiReports(array $params = [])
    {
        return $this->request('GET', '/ai/reports/{id}', null, $params, true);
    }

    /**
     * Download the report PDF.
     * GET /v1/ai/reports/{id}/pdf
     * Returns the branded PDF (application/pdf). 409 until the report is done, 410 after it expires. Send your API key header and save the file on your server. Free.
     * @param array $params Query parameters: lang.
     * @return mixed
     */
    public function aiReportsPdf(array $params = [])
    {
        return $this->request('GET', '/ai/reports/{id}/pdf', null, $params, true);
    }

    /**
     * AI products and credit prices.
     * GET /v1/ai/pricing
     * Credits per language, quality flag (standard or beta) and the languages that are not available yet. Free.
     * @param array $params Query parameters: lang.
     * @return mixed
     */
    public function aiPricing(array $params = [])
    {
        return $this->request('GET', '/ai/pricing', null, $params, true);
    }

    /**
     * Search places.
     * GET /v1/places/search
     * Find latitude, longitude and time zone for a place name.
     * @param array $params Query parameters: q*, limit.
     * @return mixed
     */
    public function placesSearch(array $params = [])
    {
        return $this->request('GET', '/places/search', null, $params, true);
    }

    /**
     * Time zone for coordinates.
     * GET /v1/timezone
     * IANA zone and UTC offset for coordinates, optionally as of a date.
     * @param array $params Query parameters: latitude*, longitude*, date.
     * @return mixed
     */
    public function timezone(array $params = [])
    {
        return $this->request('GET', '/timezone', null, $params, true);
    }

    /**
     * Your usage this month.
     * GET /v1/usage
     * Credit balance, credits and calls used today and this month with a per-endpoint breakdown, and the credit cost of every endpoint. Free: costs no credits.
     * @param array $params Query parameters.
     * @return mixed
     */
    public function usage(array $params = [])
    {
        return $this->request('GET', '/usage', null, $params, true);
    }

    /**
     * Service health.
     * GET /v1/health
     * Public status check; no key required.
     * @param array $params Query parameters.
     * @return mixed
     */
    public function health(array $params = [])
    {
        return $this->request('GET', '/health', null, $params, false);
    }
}
