<?php
declare(strict_types=1);

/**
 * EDEN RMS WhatsApp Helper
 * Providers:
 * - dev_log
 * - cloud_api
 */

if (!function_exists('wa_table_exists')) {
    function wa_table_exists(mysqli $db, string $table): bool {
        $table = $db->real_escape_string($table);
        $res = $db->query("SHOW TABLES LIKE '{$table}'");
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('wa_setting_get')) {
    function wa_setting_get(mysqli $db, string $key, string $default = ''): string {
        if (!wa_table_exists($db, 'app_settings')) return $default;

        $st = $db->prepare("SELECT v FROM app_settings WHERE k=? LIMIT 1");
        if (!$st) return $default;

        $st->bind_param('s', $key);
        $st->execute();
        $row = $st->get_result()->fetch_assoc();
        $st->close();

        return $row ? (string)$row['v'] : $default;
    }
}

if (!function_exists('wa_normalize_phone')) {
    function wa_normalize_phone(string $phone): string {
        $phone = preg_replace('/[^0-9+]/', '', trim($phone));
        if ($phone === '') return '';
        if (str_starts_with($phone, '+')) return $phone;
        if (str_starts_with($phone, '0')) return '+94' . substr($phone, 1);
        if (str_starts_with($phone, '94')) return '+' . $phone;
        return $phone;
    }
}

if (!function_exists('wa_render_template')) {
    function wa_render_template(string $message, array $data): string {
        foreach ($data as $key => $value) {
            if (is_array($value)) $value = implode("\n", $value);
            $message = str_replace('{{' . $key . '}}', (string)$value, $message);
        }
        return $message;
    }
}

if (!function_exists('wa_get_template')) {
    function wa_get_template(mysqli $db, string $templateKey): ?array {
        if (!wa_table_exists($db, 'whatsapp_templates')) return null;

        $st = $db->prepare("SELECT * FROM whatsapp_templates WHERE template_key=? LIMIT 1");
        if (!$st) return null;

        $st->bind_param('s', $templateKey);
        $st->execute();
        $row = $st->get_result()->fetch_assoc();
        $st->close();

        return $row ?: null;
    }
}

if (!function_exists('wa_log')) {
    function wa_log(
        mysqli $db,
        ?string $templateKey,
        ?int $studentId,
        ?int $paymentId,
        string $phone,
        string $provider,
        string $message,
        string $status,
        string $response = ''
    ): void {
        if (!wa_table_exists($db, 'whatsapp_logs')) return;

        $st = $db->prepare("
            INSERT INTO whatsapp_logs
            (template_key, student_id, payment_id, phone_to, provider, message_body, status, response, sent_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        if (!$st) return;

        $st->bind_param(
            'siisssss',
            $templateKey,
            $studentId,
            $paymentId,
            $phone,
            $provider,
            $message,
            $status,
            $response
        );

        $st->execute();
        $st->close();
    }
}

if (!function_exists('wa_send_cloud_api')) {
    function wa_send_cloud_api(
        mysqli $db,
        string $templateKey,
        string $phone,
        string $message,
        ?int $studentId,
        ?int $paymentId
    ): array {
        $version = wa_setting_get($db, 'wa_cloud_api_version', 'v23.0');
        $phoneNumberId = wa_setting_get($db, 'wa_phone_number_id', '');
        $token = wa_setting_get($db, 'wa_access_token', '');

        if ($phoneNumberId === '' || $token === '') {
            wa_log($db, $templateKey, $studentId, $paymentId, $phone, 'cloud_api', $message, 'failed', 'Missing Cloud API credentials');
            return ['ok' => false, 'status' => 'failed', 'error' => 'Missing credentials'];
        }

        $payload = [
    'messaging_product' => 'whatsapp',
    'to' => preg_replace('/\D+/', '', $phone),
    'type' => 'text',
    'text' => [
        'preview_url' => false,
        'body' => $message
    ]
];

        /*
         * Testing mode:
         * Meta test number normally supports hello_world template.
         * After custom templates are approved, replace hello_world with your approved template mapping.
         */
        $payload = [
    'messaging_product' => 'whatsapp',
    'to' => preg_replace('/^\+/', '', $phone),
    'type' => 'text',
    'text' => [
        'preview_url' => false,
        'body' => $message
    ]
];

        $ch = curl_init($url);

        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            ],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_TIMEOUT => 30
        ]);

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

        if ($response === false || $curlErr !== '' || $httpCode < 200 || $httpCode >= 300) {
            wa_log($db, $templateKey, $studentId, $paymentId, $phone, 'cloud_api', $message, 'failed', $curlErr ?: (string)$response);
            return ['ok' => false, 'status' => 'failed', 'http_code' => $httpCode, 'response' => $response];
        }

        wa_log($db, $templateKey, $studentId, $paymentId, $phone, 'cloud_api', $message, 'sent', (string)$response);
        return ['ok' => true, 'status' => 'sent', 'response' => $response];
    }
}

if (!function_exists('wa_send_message')) {
    function wa_send_message(
        mysqli $db,
        string $templateKey,
        string $phone,
        array $data = [],
        ?int $studentId = null,
        ?int $paymentId = null
    ): array {
        $enabled = wa_setting_get($db, 'whatsapp_enabled', '0');
        $provider = wa_setting_get($db, 'whatsapp_provider', 'dev_log');

        $phone = wa_normalize_phone($phone);

        if ($enabled !== '1') {
            wa_log($db, $templateKey, $studentId, $paymentId, $phone, $provider, '', 'skipped', 'WhatsApp globally disabled');
            return ['ok' => true, 'status' => 'skipped'];
        }

        if ($phone === '') {
            wa_log($db, $templateKey, $studentId, $paymentId, '', $provider, '', 'skipped', 'Missing phone number');
            return ['ok' => false, 'status' => 'skipped'];
        }

        $tpl = wa_get_template($db, $templateKey);

        if (!$tpl) {
            wa_log($db, $templateKey, $studentId, $paymentId, $phone, $provider, '', 'failed', 'Template not found');
            return ['ok' => false, 'status' => 'failed'];
        }

        if ((int)$tpl['is_enabled'] !== 1) {
            wa_log($db, $templateKey, $studentId, $paymentId, $phone, $provider, '', 'skipped', 'Template disabled');
            return ['ok' => true, 'status' => 'skipped'];
        }

        $message = wa_render_template((string)$tpl['message_body'], $data);

        if ($provider === 'dev_log') {
            wa_log($db, $templateKey, $studentId, $paymentId, $phone, $provider, $message, 'sent', 'DEV LOG ONLY');
            return ['ok' => true, 'status' => 'sent'];
        }

        if ($provider === 'cloud_api') {
            return wa_send_cloud_api($db, $templateKey, $phone, $message, $studentId, $paymentId);
        }

        wa_log($db, $templateKey, $studentId, $paymentId, $phone, $provider, $message, 'skipped', 'Provider not connected yet');
        return ['ok' => true, 'status' => 'skipped'];
    }
}