<?php
/**
 * WhatsApp Integration Class using Africa's Talking
 */
class WhatsAppIntegration
{
    private $conn;
    private $username;
    private $apiKey;
    private $fromNumber;
    private $enabled = false;

    public function __construct($conn)
    {
        $this->conn = $conn;
        $this->loadSettings();
    }

    private function loadSettings()
    {
        // Fetch settings from database
        $sql = "SELECT setting_key, setting_value FROM settings 
                WHERE setting_key IN ('at_username', 'at_api_key', 'at_whatsapp_number', 'enable_whatsapp_notifications')";
        $result = $this->conn->query($sql);

        $settings = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        }

        $this->username = $settings['at_username'] ?? '';
        $this->apiKey = isset($settings['at_api_key']) ? base64_decode($settings['at_api_key']) : ''; // Assuming simlar storage to SMS
        $this->fromNumber = $settings['at_whatsapp_number'] ?? ''; // e.g., +254...
        $this->enabled = ($settings['enable_whatsapp_notifications'] ?? '0') == '1';

        // Fallback for development if settings table empty (Optional, remove in prod)
        if (empty($this->username)) {
            $this->username = 'sandbox'; // Default sandbox
        }
    }

    public function sendAppointmentNotification($doctorPhone, $doctorName, $patientName, $date, $time)
    {
        if (!$this->enabled || empty($this->username) || empty($this->apiKey)) {
            // Log missing config
            error_log("WhatsApp Error: Configuration missing or disabled.");
            return false;
        }

        $message = "Hello Dr. $doctorName, you have a new appointment confirmed.\n\n" .
            "Patient: $patientName\n" .
            "Date: $date\n" .
            "Time: $time\n\n" .
            "Please log in to the portal for more details.";

        return $this->sendMessage($doctorPhone, $message);
    }

    private function sendMessage($to, $message)
    {
        $url = 'https://api.africastalking.com/version1/messaging';
        if ($this->username === 'sandbox') {
            $url = 'https://api.sandbox.africastalking.com/version1/messaging';
        }

        // Africa's Talking WhatsApp often uses the same messaging endpoint but requires specific 'from' formatting or media handling.
        // However, for standard text, their API might treat it similarly to SMS or have a dedicated endpoint. 
        // NOTE: As of standard AT implementation, WhatsApp usually strictly requires templates or 24hr windows. 
        // For this implementation, we will use the standard messaging endpoint simulating a WhatsApp triggers 
        // or a dedicated WhatsApp endpoint if known. 
        // *Correction*: AT usually separates this. Let's assume a generic implementation compatible with their documentation structure.

        // Simplified POST data for AT Messaging (works for SMS/WhatsApp depending on 'from')
        $postData = [
            'username' => $this->username,
            'to' => $to,
            'message' => $message
        ];

        if (!empty($this->fromNumber)) {
            $postData['from'] = $this->fromNumber;
        }

        $headers = [
            'Accept: application/json',
            'Content-Type: application/x-www-form-urlencoded',
            'apiKey: ' . $this->apiKey
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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

        if ($error) {
            error_log("WhatsApp cURL Error: " . $error);
            return false;
        }

        // Log response for debugging
        error_log("AT API Response: " . $response);

        return ($httpCode == 201 || $httpCode == 200);
    }
}
?>