<?php
/**
 * 优讯云OCR SDK
 * 版本: v1.0.1
 */

class YouxunOcr {
    private $apiUrl;
    private $secretId;
    private $secretKey;
    private $timeout = 30;
    
    /**
     * 构造函数
     * @param string $apiUrl API地址
     * @param string $secretId 腾讯云SecretId
     * @param string $secretKey 腾讯云SecretKey
     */
    public function __construct($apiUrl, $secretId = '', $secretKey = '') {
        $this->apiUrl = rtrim($apiUrl, '/');
        $this->secretId = $secretId;
        $this->secretKey = $secretKey;
    }
    
    /**
     * 身份证OCR识别
     * @param string $imageBase64 图片Base64编码
     * @param string $cardSide 正反面: FRONT=正面, BACK=背面
     * @param array $options 可选参数
     * @return array 返回结果
     */
    public function idcard($imageBase64 = '', $cardSide = 'FRONT', $options = []) {
        $params = [
            'SecretId' => $this->secretId,
            'SecretKey' => $this->secretKey,
            'CardSide' => $cardSide,
        ];
        
        if (!empty($imageBase64)) $params['ImageBase64'] = $imageBase64;
        if (!empty($options['ImageUrl'])) $params['ImageUrl'] = $options['ImageUrl'];
        if (!empty($options['SecretId'])) $params['SecretId'] = $options['SecretId'];
        if (!empty($options['SecretKey'])) $params['SecretKey'] = $options['SecretKey'];
        
        foreach (['CropPortrait', 'CropIdCard', 'CopyWarn', 'ReshootWarn'] as $key) {
            if (isset($options[$key])) $params[$key] = (int)$options[$key];
        }
        
        return $this->request('/api/ocr/idcard_api.php', $params);
    }
    
    private function request($endpoint, $params) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl . $endpoint);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) return ['success' => false, 'error' => 'CURL错误: ' . $error];
        
        $result = json_decode($response, true);
        return $result ?: ['success' => false, 'error' => '无效的响应数据'];
    }
    
    public function setTimeout($seconds) {
        $this->timeout = (int)$seconds;
    }
}
