<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

/**
 * StroWallet NFC Virtual Card API Client
 * PHP 7.2+ compatible — no typed properties, no union types
 *
 * CORRECT NFC Endpoints (confirmed by StroWallet support):
 *   POST create-nfc-card/         – Create NFC card
 *   GET  fetch-nfccard-detail/    – Get card details
 *   GET  nfc-card-transactions/   – Card transaction history
 *   POST fund-withdraw-nfccard/   – Fund or withdraw
 *   POST nfc-cards/status/        – Freeze or activate
 *
 * Auth: public_key sent as query param (?public_key=...)
 * Mode: mode=sandbox or mode=live sent as query param
 */
class StroWallet
{
    private $publicKey;
    private $mode;
    private $baseUrl  = 'https://strowallet.com/api/bitvcard';
    private $debugLog = '';

    public function __construct($publicKey, $sandbox = true)
    {
        $this->publicKey = $publicKey;
        $this->mode      = $sandbox ? 'sandbox' : 'live';
    }

    public function getDebugLog()
    {
        return $this->debugLog;
    }

    // ══════════════════════════════════════════════════════════
    //  CORE HTTP — params go in query string per docs example
    // ══════════════════════════════════════════════════════════

    /**
     * POST — params sent as query string (as shown in their PHP example)
     */
    private function post($endpoint, $params = array())
    {
        $params['public_key'] = $this->publicKey;
        $params['mode']       = $this->mode;

        $url = $this->baseUrl . '/' . ltrim($endpoint, '/') . '?' . http_build_query($params);

        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => '',   // empty body — all params in query string
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPHEADER     => array('Accept: application/json'),
        ));

        $response = curl_exec($ch);
        $curlErr  = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $effUrl   = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        curl_close($ch);

        $safeParams = $params;
        $this->debugLog = "METHOD: POST\nURL: {$effUrl}\nHTTP: {$httpCode}\nPARAMS: " . json_encode($safeParams) . "\nRESPONSE: " . $response . "\nCURL_ERR: " . ($curlErr ? $curlErr : 'none');

        return $this->parse($response, $curlErr, $httpCode);
    }

    /**
     * GET — params sent as query string
     */
    private function get($endpoint, $params = array())
    {
        $params['public_key'] = $this->publicKey;
        $params['mode']       = $this->mode;

        $url = $this->baseUrl . '/' . ltrim($endpoint, '/') . '?' . http_build_query($params);

        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPHEADER     => array('Accept: application/json'),
        ));

        $response = curl_exec($ch);
        $curlErr  = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $effUrl   = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        curl_close($ch);

        $this->debugLog = "METHOD: GET\nURL: {$effUrl}\nHTTP: {$httpCode}\nRESPONSE: " . $response . "\nCURL_ERR: " . ($curlErr ? $curlErr : 'none');

        return $this->parse($response, $curlErr, $httpCode);
    }

    private function parse($response, $curlErr, $httpCode)
    {
        if ($curlErr) {
            return array('success' => false, 'error' => 'cURL error: ' . $curlErr, 'code' => 0, 'data' => null, 'raw' => null);
        }
        if (empty($response)) {
            return array('success' => false, 'error' => 'Empty response (HTTP ' . $httpCode . ')', 'code' => $httpCode, 'data' => null, 'raw' => null);
        }

        $decoded = json_decode($response, true);
        if ($decoded === null) {
            return array('success' => false, 'error' => 'Invalid JSON: ' . substr($response, 0, 300), 'raw' => $response, 'code' => $httpCode, 'data' => null);
        }

        $success = false;
        if (isset($decoded['status'])) {
            $s       = $decoded['status'];
            $success = ($s === true || $s === 'success' || $s === 'Success' || $s === 1 || $s === '1');
        } elseif ($httpCode >= 200 && $httpCode < 300) {
            $success = true;
        }

        // NFC endpoints nest data under 'response' key
        if (isset($decoded['response'])) {
            $data = $decoded['response'];
        } elseif (isset($decoded['data'])) {
            $data = $decoded['data'];
        } elseif (isset($decoded['info'])) {
            $data = $decoded['info'];
        } else {
            $data = $decoded;
        }

        $error = null;
        if (!$success) {
            if (isset($decoded['message'])) $error = $decoded['message'];
            elseif (isset($decoded['error'])) $error = $decoded['error'];
            elseif (isset($decoded['msg']))   $error = $decoded['msg'];
            else $error = 'StroWallet error (HTTP ' . $httpCode . ')';
        }

        return array(
            'success' => $success,
            'data'    => $data,
            'raw'     => $decoded,
            'error'   => $error,
            'code'    => $httpCode,
        );
    }

    // ══════════════════════════════════════════════════════════
    //  NFC CARD CREATION
    //  POST create-nfc-card/
    //  Params: public_key, name, first_name, last_name, dob (mm/dd/yyyy),
    //          id_type, id_number, email, line1, city, state,
    //          postal_code, country (3-letter e.g. NGA), amount_usd, phone
    // ══════════════════════════════════════════════════════════
    public function createCard($params)
    {
        return $this->post('create-nfc-card/', $params);
    }

    // ══════════════════════════════════════════════════════════
    //  NFC CARD DETAILS
    //  GET fetch-nfccard-detail/
    //  Params: public_key, card_id
    // ══════════════════════════════════════════════════════════
    public function getCardDetails($cardId)
    {
        return $this->get('fetch-nfccard-detail/', array('card_id' => $cardId));
    }

    // ══════════════════════════════════════════════════════════
    //  NFC CARD TRANSACTION HISTORY
    //  GET nfc-card-transactions/
    //  Params: public_key, card_id
    // ══════════════════════════════════════════════════════════
    public function getCardTransactions($cardId)
    {
        return $this->get('nfc-card-transactions/', array('card_id' => $cardId));
    }

    // ══════════════════════════════════════════════════════════
    //  FUND CARD
    //  POST fund-withdraw-nfccard/
    //  Params: public_key, card_id, amount, type="fund"
    // ══════════════════════════════════════════════════════════
    public function fundCard($cardId, $amount)
    {
        return $this->post('fund-withdraw-nfccard/', array(
            'card_id' => $cardId,
            'amount'  => (string)$amount,
            'type'    => 'fund',
        ));
    }

    // ══════════════════════════════════════════════════════════
    //  WITHDRAW FROM CARD
    //  POST fund-withdraw-nfccard/
    //  Params: public_key, card_id, amount, type="withdraw"
    // ══════════════════════════════════════════════════════════
    public function withdrawFromCard($cardId, $amount)
    {
        return $this->post('fund-withdraw-nfccard/', array(
            'card_id' => $cardId,
            'amount'  => (string)$amount,
            'type'    => 'withdraw',
        ));
    }

    // ══════════════════════════════════════════════════════════
    //  FREEZE CARD
    //  POST nfc-cards/status/
    //  Params: public_key, card_id, status="frozen"
    // ══════════════════════════════════════════════════════════
    public function freezeCard($cardId)
    {
        return $this->post('nfc-cards/status/', array(
            'card_id' => $cardId,
            'status'  => 'frozen',
        ));
    }

    // ══════════════════════════════════════════════════════════
    //  ACTIVATE / UNFREEZE CARD
    //  POST nfc-cards/status/
    //  Params: public_key, card_id, status="active"
    // ══════════════════════════════════════════════════════════
    public function unfreezeCard($cardId)
    {
        return $this->post('nfc-cards/status/', array(
            'card_id' => $cardId,
            'status'  => 'active',
        ));
    }
}