<?php

require_once __DIR__ . '/../config/Database.php';

class WhatsAppService
{

    private $db;

    public function __construct()
    {
        $this->db = Database::getInstance()->getConnection();
    }

    /**
     * Send OTP via WhatsApp using Wablas API
     */
    public function sendOTP($phone, $otp)
    {
        try {
            // Get WhatsApp bot configuration
            $botConfig = $this->getBotConfig();
            if (!$botConfig) {
                throw new Exception("WhatsApp bot configuration not found");
            }

            // Prepare message
            $message = "Kode OTP EPasadana Anda: *{$otp}*\n\nKode ini berlaku selama 5 menit.\nJangan bagikan kode ini kepada siapa pun.\n\nTerima kasih.";

            // Prepare data for Wablas API
            $data = [
                'phone' => $phone,
                'message' => $message,
                'secret' => false,
                'retry' => false,
                'isGroup' => false
            ];

            // Send WhatsApp message
            $result = $this->sendWablasMessage($botConfig, $data);

            // Log the attempt
            $this->logWhatsAppAttempt($phone, $otp, $result);

            return $result;
        } catch (Exception $e) {
            error_log("WhatsApp OTP send error: " . $e->getMessage());
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    /**
     * Get bot configuration from database
     */
    private function getBotConfig()
    {
        $stmt = $this->db->prepare("SELECT token, secretkey FROM bot WHERE id = 9 LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->execute();
        $result = $stmt->get_result();
        $config = $result->fetch_assoc();
        $stmt->close();

        return $config;
    }

    /**
     * Send message via Wablas API
     */
    private function sendWablasMessage($botConfig, $data)
    {
        $curl = curl_init();

        $headers = [
            'Authorization: ' . $botConfig['token'],
            'Content-Type: application/x-www-form-urlencoded'
        ];

        $postData = array_merge($data, ['secret' => $botConfig['secretkey']]);

        curl_setopt_array($curl, [
            CURLOPT_URL => "https://pati.wablas.com/api/send-message",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => http_build_query($postData),
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        curl_close($curl);

        if ($error) {
            throw new Exception("CURL Error: " . $error);
        }

        $result = json_decode($response, true);

        if ($httpCode === 200 && $result) {
            return [
                'success' => true,
                'message' => 'WhatsApp sent successfully',
                'response' => $result
            ];
        } else {
            return [
                'success' => false,
                'message' => 'Failed to send WhatsApp',
                'http_code' => $httpCode,
                'response' => $response
            ];
        }
    }

    /**
     * Log WhatsApp attempt
     */
    private function logWhatsAppAttempt($phone, $otp, $result)
    {
        $logDir = __DIR__ . '/../log/';
        if (!file_exists($logDir)) {
            mkdir($logDir, 0755, true);
        }

        $logFile = $logDir . 'logs_get_otp_wa_' . date('Ymd') . '.txt';
        $timestamp = date('Y-m-d H:i:s');
        $status = $result['success'] ? 'SUCCESS' : 'FAILED';
        $message = $result['message'] ?? 'Unknown error';

        $logEntry = "[$timestamp] $status - Phone: $phone, OTP: $otp, Message: $message\n";

        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    }

    /**
     * Send custom WhatsApp message
     */
    public function sendMessage($phone, $message)
    {
        try {
            $botConfig = $this->getBotConfig();
            if (!$botConfig) {
                throw new Exception("WhatsApp bot configuration not found");
            }

            $data = [
                'phone' => $phone,
                'message' => $message,
                'secret' => false,
                'retry' => false,
                'isGroup' => false
            ];

            return $this->sendWablasMessage($botConfig, $data);
        } catch (Exception $e) {
            error_log("WhatsApp message send error: " . $e->getMessage());
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}
