<?php
/**
 * Fusion Wayne v3 - API Client (para endpoints provistos)
 * Autor: ChatGPT
 */
declare(strict_types=1);

class FusionApiClient {
    private string $base;
    private int $timeout;
    private ?string $token;
    private ?array $basic;
    private ?string $cookies;
    private bool $verifySSL;

    public function __construct(string $base, int $timeout=8, ?string $token=null, ?array $basic=null, ?string $cookies=null, bool $verifySSL=false){
        $this->base = rtrim($base, '/');
        $this->timeout = $timeout;
        $this->token = $token;
        $this->basic = $basic;
        $this->cookies = $cookies;
        $this->verifySSL = $verifySSL;
    }

    private function request(string $method, string $path, $payload=null, array $headers=[]): array {
        $ch = curl_init();
        $url = $this->base . '/' . ltrim($path, '/');
        $hs = [];
        foreach ($headers as $k=>$v) $hs[] = $k . ': ' . $v;
        if ($this->token) $hs[] = 'Authorization: Bearer ' . $this->token;

        curl_setopt_array($ch,[
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_CUSTOMREQUEST => strtoupper($method),
            CURLOPT_HTTPHEADER => $hs,
            CURLOPT_SSL_VERIFYPEER => $this->verifySSL,
            CURLOPT_SSL_VERIFYHOST => $this->verifySSL ? 2 : 0,
        ]);
        if ($this->cookies) curl_setopt($ch, CURLOPT_COOKIE, $this->cookies);
        if ($payload !== null) {
            if (is_array($payload)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
                $hs[] = 'Content-Type: application/x-www-form-urlencoded';
                curl_setopt($ch, CURLOPT_HTTPHEADER, $hs);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, (string)$payload);
            }
        }
        if ($this->basic && isset($this->basic['user'])) {
            curl_setopt($ch, CURLOPT_USERPWD, $this->basic['user'].':'.($this->basic['pass'] ?? ''));
        }
        $raw = curl_exec($ch);
        $err = curl_error($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($err !== '') return ['ok'=>false, 'status'=>$code, 'error'=>$err, 'data'=>null];
        $data = json_decode($raw, true);
        return ['ok'=>($code>=200 && $code<300), 'status'=>$code, 'data'=>$data, 'raw'=>$raw];
    }

    // === Endpoints provistos ===
    public function getPrices(){                      return $this->request('GET',  '/api/prices.php'); }
    public function getSales(string $init=null, string $end=null){
        $path = '/api/sales.php';
        if ($init !== null || $end !== null) {
            $q = [];
            if ($init !== null) $q['init'] = $init;
            if ($end  !== null) $q['end']  = $end;
            $path .= '?' . http_build_query($q);
        }
        return $this->request('GET', $path);
    }
    public function getVolumeByHose(){               return $this->request('GET',  '/api/volumeByHose.php'); }
    public function getAttendants(){                 return $this->request('GET',  '/api/attendant.php'); }
    public function getAlarms(){                     return $this->request('GET',  '/api/alarms.php'); }
    public function getSystemModules(){              return $this->request('GET',  '/api/modules.php'); }
    public function getTanks(){                      return $this->request('GET',  '/api/tanks.php'); }
    public function changeGlanceRedirect(?bool $flag){
        // si $flag es null => solo consulta; true/false => set y devuelve estado
        $path = '/api/changeRedirect.php';
        if ($flag !== null) $path .= '?glanceredirect=' . ($flag ? 'true' : 'false');
        return $this->request('GET', $path);
    }
    public function translate(string $q){            return $this->request('GET',  '/api/translate.php?q='.rawurlencode($q)); }
}
