<?php

namespace Core\App\Controllers;

use Core\App\Services\WhatsAppService;

class WhatsappController
{
    /* =====================================================
       SETTINGS PAGE
    ===================================================== */
    public function settings()
    {
        $whatsapp = $this->loadConfig();

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/settings/whatsapp.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =====================================================
       SAVE SETTINGS
    ===================================================== */
    public function save()
    {
        $provider  = $_POST['provider']   ?? 'callmebot';
        $isActive  = isset($_POST['is_active']) ? 1 : 0;

        $defaults = $this->defaultConfig();

        $config = [
            'provider' => $provider,
            'events'   => [
                'order_confirmed'   => isset($_POST['event_confirmed'])  ? 1 : 0,
                'order_shipped'     => isset($_POST['event_shipped'])    ? 1 : 0,
                'status_updated'    => isset($_POST['event_status'])     ? 1 : 0,
                'meeting_reminder'  => isset($_POST['event_meeting'])    ? 1 : 0,
            ],
            'templates' => [
                'order_confirmed'  => trim($_POST['tpl_confirmed']  ?? '') ?: (string)$defaults['templates']['order_confirmed'],
                'order_shipped'    => trim($_POST['tpl_shipped']     ?? '') ?: (string)$defaults['templates']['order_shipped'],
                'status_updated'   => trim($_POST['tpl_status']      ?? '') ?: (string)$defaults['templates']['status_updated'],
                'meeting_reminder' => trim($_POST['tpl_meeting'] ?? '') ?: (string)$defaults['templates']['meeting_reminder'],
            ],
        ];

        // Provider-specific credentials
        switch ($provider) {
            case 'callmebot':
                $config['callmebot_apikey'] = trim($_POST['callmebot_apikey'] ?? '');
                break;
            case 'twilio':
                $config['twilio_sid']   = trim($_POST['twilio_sid']   ?? '');
                $config['twilio_token'] = trim($_POST['twilio_token'] ?? '');
                $config['twilio_from']  = trim($_POST['twilio_from']  ?? '');
                break;
            case 'meta':
                $config['meta_token']    = trim($_POST['meta_token']    ?? '');
                $config['meta_phone_id'] = trim($_POST['meta_phone_id'] ?? '');
                break;
            case 'ultramsg':
                $config['ultramsg_instance'] = trim($_POST['ultramsg_instance'] ?? '');
                $config['ultramsg_token']    = trim($_POST['ultramsg_token']    ?? '');
                break;
        }

        $db = \db();

        // upsert
        $check = $db->prepare("SELECT id FROM tracking_integrations WHERE provider = 'whatsapp' LIMIT 1");
        $check->execute();

        if ($check->fetchColumn()) {
            $db->prepare("
                UPDATE tracking_integrations
                SET config = :config, is_active = :active, updated_at = NOW()
                WHERE provider = 'whatsapp'
            ")->execute([
                ':config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                ':active' => $isActive,
            ]);
        } else {
            $db->prepare("
                INSERT INTO tracking_integrations (provider, is_active, config)
                VALUES ('whatsapp', :active, :config)
            ")->execute([
                ':config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                ':active' => $isActive,
            ]);
        }

        $_SESSION['flash_success'] = __('whatsapp.saved', 'WhatsApp settings saved successfully');
        header('Location: /admin/settings/whatsapp');
        exit;
    }

    /* =====================================================
       TEST SEND
    ===================================================== */
    public function test()
    {
        header('Content-Type: application/json; charset=utf-8');

        $phone   = trim($_POST['phone']   ?? '');
        $message = trim($_POST['message'] ?? 'Test message from ' . ($_SERVER['HTTP_HOST'] ?? 'store'));

        if (!$phone) {
            echo json_encode(['success' => false, 'error' => 'Phone number required']);
            exit;
        }

        $service = WhatsAppService::fromSettings();
        if (!$service) {
            echo json_encode(['success' => false, 'error' => 'WhatsApp not configured or disabled']);
            exit;
        }

        $testOrder = [
            'id' => 0,
            'full_name' => 'Test User',
            'phone' => $phone,
            'address' => '',
            'city_name' => '',
            'total_amount' => 0,
            'extra' => [
                'pricing' => ['currency' => 'DZD', 'total' => 0],
                'product' => ['name' => 'Test Product'],
                'shipping' => [
                    'provider' => (string)$service->getProvider(),
                    'tracking' => 'TEST123',
                    'status' => 'test',
                    'destination' => ['city_name' => ''],
                ],
            ],
        ];

        $message = WhatsAppService::buildMessage($message, $testOrder);
        $result = $service->send($phone, $message, [
            'event' => 'test',
            'type'  => 'auto',
        ]);
        echo json_encode($result);
        exit;
    }

    /* =====================================================
       HELPER
    ===================================================== */
    private function loadConfig(): array
    {
        try {
            $stmt = \db()->prepare("
                SELECT is_active, config FROM tracking_integrations
                WHERE provider = 'whatsapp' LIMIT 1
            ");
            $stmt->execute();
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);

            if (!$row) return $this->defaultConfig();

            $cfg = json_decode($row['config'], true) ?: [];
            if (empty(trim((string)($cfg['templates']['meeting_reminder'] ?? '')))) {
                $cfg['templates']['meeting_reminder'] = $this->defaultConfig()['templates']['meeting_reminder'];
            }
            $cfg['is_active'] = (int)$row['is_active'];
            return $this->mergeConfig($this->defaultConfig(), $cfg);
        } catch (\Throwable $e) {
            return $this->defaultConfig();
        }
    }


    private function mergeConfig(array $defaults, array $config): array
    {
        foreach ($config as $key => $value) {
            if (is_array($value) && isset($defaults[$key]) && is_array($defaults[$key])) {
                $defaults[$key] = $this->mergeConfig($defaults[$key], $value);
            } else {
                $defaults[$key] = $value;
            }
        }

        return $defaults;
    }

    private function defaultConfig(): array
    {
        $lang = \Core\System\Language::code();
        $meetingTpl = $lang === 'ar'
            ? "📅 تذكير بالاجتماع!
مرحبًا {attendee_name}، لديك اجتماع خلال {minutes_left} دقائق.
اجتماع: {meeting_title}
الوقت: {meeting_time}
نراكم هناك! 👋"
            : "📅 Meeting Reminder!
Hello {attendee_name}, you have a meeting in {minutes_left} minutes.
Meeting: {meeting_title}
Time: {meeting_time}
See you there! 👋";

        return [
            'is_active' => 0,
            'provider'  => 'callmebot',
            'events'    => [
                'order_confirmed'  => 1,
                'order_shipped'    => 1,
                'status_updated'   => 0,
                'meeting_reminder' => 1,
            ],
            'templates' => [
                'order_confirmed'  => "Hello {name}! 🎉
Your order {order_id} has been confirmed.
Product: {product}
Total: {total}
Thank you for shopping with {store_name}!",
                'order_shipped'    => "Hello {name}! 📦
Your order {order_id} has been shipped via {provider}.
Tracking: {tracking}
City: {city}",
                'status_updated'   => "Hello {name}! 🚚
Order {order_id} update: {status}
Tracking: {tracking}",
                'meeting_reminder' => $meetingTpl,
            ],
            'callmebot_apikey'   => '',
            'twilio_sid'         => '',
            'twilio_token'       => '',
            'twilio_from'        => '',
            'meta_token'         => '',
            'meta_phone_id'      => '',
            'ultramsg_instance'  => '',
            'ultramsg_token'     => '',
        ];
    }

    /**
     * WhatsApp Messages Log
     */
    public function logs(): void
    {
        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/settings/whatsapp_logs/index.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }
}
