<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Setting;
use App\Models\Contact;
use App\Models\Message;
use App\Controllers\WebhookController;

class SettingsController extends Controller {
    public function index(): void {
        $settings = Setting::getAllGrouped();
        $this->render('settings/index', ['settings' => $settings]);
    }

    public function update(): void {
        $fields = [
            'whatsapp_driver'            => 'whatsapp',
            'gateway_instance_id'        => 'gateway',
            'gateway_token'              => 'gateway',
            'gateway_api_url'            => 'gateway',
            'app_name'                   => 'general',
            'company_name'               => 'general',
            'timezone'                   => 'general',
            'currency_symbol'            => 'general',
            'whatsapp_phone_number_id'   => 'meta',
            'whatsapp_waba_id'           => 'meta',
            'whatsapp_access_token'      => 'meta',
            'whatsapp_verify_token'      => 'meta',
            'whatsapp_app_secret'        => 'meta',
            'whatsapp_api_version'       => 'meta',
            'webhook_simulator_enabled'  => 'general'
        ];

        foreach ($fields as $key => $group) {
            if (isset($_POST[$key])) {
                Setting::setVal($key, trim($_POST[$key]), $group);
            }
        }

        if (Request::isAjax()) {
            Response::success(null, 'Settings updated successfully');
        }
        Response::redirect('/settings?success=saved');
    }

    /**
     * Proxy endpoint to check local WhatsApp Web Node.js microservice status & QR code
     */
    public function getLocalQrStatus(): void {
        $ch = curl_init("http://localhost:3000/status");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 2
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200 && $response) {
            $data = json_decode($response, true);
            Response::success($data);
        } else {
            Response::json([
                'success'      => false,
                'status'       => 'server_offline',
                'message'      => 'WhatsApp Web Server is not running. Launch it with start-whatsapp-qr.bat',
                'is_connected' => false,
                'qr_image'     => null
            ]);
        }
    }

    /**
     * Proxy endpoint to logout local WhatsApp Web session
     */
    public function logoutLocalQr(): void {
        $ch = curl_init("http://localhost:3000/logout");
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 5
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        Response::success(json_decode($response, true) ?: null, 'Logged out from WhatsApp Web');
    }

    public function simulator(): void {
        $contacts = Contact::all('updated_at DESC');
        $this->render('settings/simulator', ['contacts' => $contacts]);
    }

    public function simulateIncomingMessage(): void {
        $phone = trim(Request::post('phone_number', '15550192834'));
        $name = trim(Request::post('name', 'WhatsApp Tester'));
        $text = trim(Request::post('message', 'Hello, this is a test message from WhatsApp!'));
        $msgType = Request::post('message_type', 'text');
        $mediaUrl = Request::post('media_url');

        $whatsappId = preg_replace('/[^0-9]/', '', $phone);
        if (empty($whatsappId)) {
            Response::error('Valid phone number required');
        }

        $mockPayload = [
            'from'      => $whatsappId,
            'id'        => 'wamid.SIM_' . bin2hex(random_bytes(8)),
            'timestamp' => time(),
            'type'      => $msgType
        ];

        if ($msgType === 'text') {
            $mockPayload['text'] = ['body' => $text];
        } elseif ($msgType === 'image') {
            $mockPayload['image'] = ['link' => $mediaUrl ?: 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=600', 'caption' => $text];
        }

        $webhookCtrl = new WebhookController();
        $webhookCtrl->handleInboundMessage($mockPayload, $name);

        Response::success($mockPayload, "Simulated message received from {$name} ({$phone})!");
    }

    public function simulateStatusUpdate(): void {
        $metaMsgId = Request::post('meta_message_id');
        $status = Request::post('status', 'read');

        if (empty($metaMsgId)) {
            Response::error('Meta Message ID is required');
        }

        Message::updateStatusByMetaId($metaMsgId, $status);
        Response::success(null, "Message status updated to '{$status}'");
    }
}
