<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SmsGateway extends Model
{
    use HasFactory;

    protected $table = 'sms_gateways';
    
    protected $fillable = [
        'name',
        'provider',
        'api_url',
        'api_key',
        'secret_key',
        'sender_id',
        'username',
        'password',
        'parameters',
        'is_default',
        'is_active',
        'balance',
        'last_checked'
    ];

    protected $casts = [
        'parameters' => 'array',
        'is_default' => 'boolean',
        'is_active' => 'boolean',
        'balance' => 'decimal:2',
        'last_checked' => 'datetime'
    ];

    // Available providers
    public static function getProviders()
    {
        return [
            'bulksmsbd' => 'BulkSMSBD',
            'greenweb' => 'GreenWeb',
            'ssl' => 'SSL Wireless',
            'twilio' => 'Twilio',
            'revesms' => 'Reve SMS',
            'custom' => 'Custom API'
        ];
    }

    // Get default gateway
    public static function getDefault()
    {
        return self::where('is_default', true)->where('is_active', true)->first();
    }

    // Send SMS through this gateway
    public function send($phone, $message)
    {
        switch ($this->provider) {
            case 'bulksmsbd':
                return $this->sendBulkSmsBD($phone, $message);
            case 'greenweb':
                return $this->sendGreenWeb($phone, $message);
            case 'ssl':
                return $this->sendSSL($phone, $message);
            case 'twilio':
                return $this->sendTwilio($phone, $message);
            default:
                return $this->sendCustom($phone, $message);
        }
    }

    // BulkSMSBD Provider
    private function sendBulkSmsBD($phone, $message)
    {
        $url = $this->api_url ?? 'http://api.bulksmsbd.com/smsapi';
        
        $params = [
            'api_key' => $this->api_key,
            'senderid' => $this->sender_id,
            'number' => $phone,
            'message' => $message,
            'type' => 'text'
        ];

        return $this->httpPost($url, $params);
    }

    // GreenWeb Provider
    private function sendGreenWeb($phone, $message)
    {
        $url = $this->api_url ?? 'http://api.greenweb.com.bd/api.php';
        
        $params = [
            'token' => $this->api_key,
            'to' => $phone,
            'message' => $message
        ];

        return $this->httpPost($url, $params);
    }

    // SSL Wireless Provider
    private function sendSSL($phone, $message)
    {
        $url = $this->api_url ?? 'https://sms.sslwireless.com/pushapi/dynamic/server.php';
        
        $params = [
            'api_token' => $this->api_key,
            'sid' => $this->sender_id,
            'msisdn' => $phone,
            'sms' => $message,
            'csms_id' => uniqid()
        ];

        return $this->httpPost($url, $params);
    }

    // Twilio Provider
    private function sendTwilio($phone, $message)
    {
        // Requires Twilio SDK
        // Implement as needed
        return false;
    }

    // Custom Provider
    private function sendCustom($phone, $message)
    {
        $params = $this->parameters ?? [];
        
        // Replace placeholders
        foreach ($params as $key => $value) {
            $params[$key] = str_replace('{phone}', $phone, $value);
            $params[$key] = str_replace('{message}', $message, $value);
        }

        return $this->httpPost($this->api_url, $params);
    }

    // HTTP POST request
    private function httpPost($url, $params)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            return ['success' => false, 'error' => $error];
        }

        return ['success' => true, 'response' => $response];
    }

    // Check balance
    public function checkBalance()
    {
        // Implement balance check for each provider
        // This is a simplified version
        $this->last_checked = now();
        $this->save();
        
        return $this->balance;
    }
}