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

/**
 * CheapDataHub API Client — v2
 * Docs: https://www.cheapdatahub.ng/api/docs/
 * Base URL : https://www.cheapdatahub.ng/api/v1/resellers/
 * Auth     : Authorization: Bearer YOUR_API_KEY  (header)
 * Response : { "status": "true"|"false", "message": "...", ... }
 *
 * CONFIRMED API field names (tested 2026-04-01):
 *   Airtime:     provider_id, phone_number, amount
 *   Data:        bundle_id, phone_number
 *   Cable:       provider_id, plan_id, cardnumber, phone
 *   Electricity: disco_id, meter_number, amount, phone, meter_type
 */
class CheapDataHub {

    private $api_key;
    private $base_url;

    // Network name → provider_id  (from docs)
    const NETWORK_IDS = [
        'MTN'     => 1,
        'GLO'     => 2,
        'AIRTEL'  => 3,
        '9MOBILE' => 4,
    ];

    // Cable provider name → provider_id (confirmed via API testing)
    // GOTV=1, DSTV=2, STARTIMES=3
    const CABLE_PROVIDER_IDS = [
        'GOTV'      => 1,
        'DSTV'      => 2,
        'STARTIMES' => 3,
    ];

    // DISCO name → disco_id  (from docs)
    const DISCO_IDS = [
        'AEDC'  => 1,   // Abuja Electric
        'EKEDC' => 2,   // Eko Electric
        'IBEDC' => 3,   // Ibadan Electric
        'IKEDC' => 4,   // Ikeja Electric
        'KEDC'  => 5,   // Kaduna Electric
        'PHEDC' => 6,   // Port Harcourt Electric
        'JEDC'  => 7,   // Jos Electric
        'EEDC'  => 8,   // Enugu Electric
        'YEDC'  => 9,   // Yola Electric
        'BEDC'  => 10,  // Benin Electric
    ];

    public function __construct(
        string $api_key,
        string $base_url = 'https://www.cheapdatahub.ng/api/v1/resellers'
    ) {
        $this->api_key  = $api_key;
        $this->base_url = rtrim($base_url, '/');
    }

    // ── Core HTTP POST ────────────────────────────────────────────────────────

    private function post(string $endpoint, array $data): array {
        $url = $this->base_url . '/' . ltrim($endpoint, '/');

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . $this->api_key,
                'Content-Type: application/json',
                'Accept: application/json',
            ],
        ]);

        $response  = curl_exec($ch);
        $curl_err  = curl_error($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($curl_err) {
            return ['success' => false, 'error' => 'cURL error: ' . $curl_err, 'code' => 0];
        }
        if (empty($response)) {
            return ['success' => false, 'error' => 'Empty response (HTTP ' . $http_code . ')', 'code' => $http_code];
        }

        $decoded = json_decode($response, true);
        if ($decoded === null) {
            return ['success' => false, 'error' => 'Invalid JSON response', 'raw' => $response, 'code' => $http_code];
        }

        // CDH returns "status": "true" (string) on success
        $ok = isset($decoded['status']) && (
            $decoded['status'] === 'true'    ||
            $decoded['status'] === true      ||
            $decoded['status'] === 'success'
        );

        return [
            'success' => $ok,
            'data'    => $decoded,
            'error'   => $ok ? null : ($decoded['message'] ?? $decoded['error'] ?? 'Unknown error from provider'),
            'code'    => $http_code,
        ];
    }

    // ── Core HTTP GET ─────────────────────────────────────────────────────────

    private function get(string $endpoint, array $params = []): array {
        $url = $this->base_url . '/' . ltrim($endpoint, '/');
        if ($params) $url .= '?' . http_build_query($params);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . $this->api_key,
                'Accept: application/json',
            ],
        ]);

        $response = curl_exec($ch);
        $curl_err = curl_error($ch);
        curl_close($ch);

        if ($curl_err) return ['success' => false, 'error' => 'cURL error: ' . $curl_err];
        $decoded = json_decode($response, true);
        if ($decoded === null) return ['success' => false, 'error' => 'Invalid JSON', 'raw' => $response];

        $ok = isset($decoded['status']) && (
            $decoded['status'] === 'true' || $decoded['status'] === true || $decoded['status'] === 'success'
        );
        return ['success' => $ok, 'data' => $decoded, 'error' => $ok ? null : ($decoded['message'] ?? 'Unknown error')];
    }

    // ════════════════════════════════════════════════════════════
    //  BALANCE
    // ════════════════════════════════════════════════════════════

    public function getBalance(): array {
        return $this->get('balance/');
    }

    // ══════════════════���═════════════════════════════════════════
    //  AIRTIME  POST /airtime/purchase/
    //  Fields: provider_id, phone_number, amount
    //  DO NOT MODIFY — WORKING
    // ════════════════════════════════════════════════════════════

    public function buyAirtime(string $network, string $phone, float $amount): array {
        $provider_id = self::NETWORK_IDS[strtoupper($network)] ?? null;
        if (!$provider_id) {
            return ['success' => false, 'error' => 'Unknown network: ' . $network];
        }
        return $this->post('airtime/purchase/', [
            'provider_id'  => $provider_id,
            'phone_number' => $phone,
            'amount'       => $amount,
        ]);
    }

    // ════════════════════════════════════════════════════════════
    //  DATA  POST /data/purchase/
    //  Fields: bundle_id, phone_number
    //  DO NOT MODIFY — WORKING
    // ════════════════════════════════════════════════════════════

    public function buyData(string $phone, int $bundle_id): array {
        return $this->post('data/purchase/', [
            'bundle_id'    => $bundle_id,
            'phone_number' => $phone,
        ]);
    }

    // ════════════════════════════════════════════════════════════
    //  CABLE TV  POST /cable/purchase/
    //
    //  CONFIRMED fields (tested 2026-04-01):
    //    provider_id — numeric: GOTV=1, DSTV=2, STARTIMES=3
    //    plan_id     — numeric plan code from vtu_cable_plans.plan_code
    //    cardnumber  — decoder smartcard/IUC number
    //    phone       — customer phone for SMS confirmation
    // ════════════════════════════════════════════════════════════

    public function buyCable(string $provider, string $card_no, $plan_code, string $phone): array {
        $provider_id = self::CABLE_PROVIDER_IDS[strtoupper($provider)] ?? null;
        if (!$provider_id) {
            return ['success' => false, 'error' => 'Unknown cable provider: ' . $provider];
        }

        return $this->post('cable/purchase/', [
            'provider_id' => $provider_id,
            'plan_id'     => (int)$plan_code,
            'cardnumber'  => $card_no,
            'phone'       => $phone,
        ]);
    }

    // ════════════════════════════════════════════════════════════
    //  ELECTRICITY  POST /electricity/purchase/
    //
    //  CONFIRMED fields (tested 2026-04-01):
    //    disco_id     — numeric ID (AEDC=1, EKEDC=2, etc.)
    //    meter_number — customer meter number
    //    amount       — amount in NGN (min ₦1,000)
    //    phone        — customer phone for token SMS
    //    meter_type   — "prepaid" or "postpaid"
    // ════════════════════════════════════════════════════════════

    public function buyElectricity(
        string $disco,
        string $meter_no,
        float  $amount,
        string $type  = 'prepaid',
        string $phone = ''
    ): array {
        $disco_id = self::DISCO_IDS[strtoupper($disco)] ?? null;
        if (!$disco_id) {
            return ['success' => false, 'error' => 'Unknown DISCO: ' . $disco];
        }

        return $this->post('electricity/purchase/', [
            'disco_id'     => $disco_id,
            'meter_number' => $meter_no,
            'amount'       => $amount,
            'phone'        => $phone,
            'meter_type'   => $type,
        ]);
    }

    // ── Static helpers ────────────────────────────────────────────────────────

    public static function getNetworkId(string $network): ?int {
        return self::NETWORK_IDS[strtoupper($network)] ?? null;
    }

    public static function getDiscoId(string $disco): ?int {
        return self::DISCO_IDS[strtoupper($disco)] ?? null;
    }

    public static function getCableProviderId(string $provider): ?int {
        return self::CABLE_PROVIDER_IDS[strtoupper($provider)] ?? null;
    }
}