<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Database;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Services\ActivityLogger;
use App\Services\ChatbotService;

final class ChatbotController extends BaseController
{
    // ---- Public widget endpoints (no auth — visitors on the marketing site) ----

    public function start(Request $request): Response
    {
        $businessLineId = (int) $request->input('business_line_id');
        if ($businessLineId <= 0) {
            return AjaxResponse::error('business_line_id is required.', 422);
        }

        $result = (new ChatbotService())->startConversation($businessLineId, $request->ip());

        return AjaxResponse::success($result);
    }

    public function message(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'conversation_id' => 'required|integer',
            'message' => 'required|string|max:1000',
            'business_line_id' => 'required|integer|exists:business_lines,id',
        ]);

        $result = (new ChatbotService())->handleMessage((int) $data['conversation_id'], $data['message'], (int) $data['business_line_id']);

        return AjaxResponse::success($result);
    }

    // ---- Admin: chatbot settings (per business line) ----

    public function settings(Request $request): Response
    {
        $rows = Database::connection()->query(
            'SELECT cs.*, bl.name AS business_line_name FROM chatbot_settings cs JOIN business_lines bl ON bl.id = cs.business_line_id ORDER BY bl.name'
        )->fetchAll();

        return $this->view('ai/chatbot-settings', [
            'title' => 'Website Chatbot',
            'activeNav' => 'chatbot',
            'breadcrumbs' => [['Home', 'dashboard'], ['AI', 'ai-assistant'], ['Website Chatbot', 'chatbot-settings']],
            'rows' => $rows,
            'businessLines' => Database::connection()->query('SELECT id, name FROM business_lines ORDER BY name')->fetchAll(),
        ]);
    }

    public function updateSettings(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'business_line_id' => 'required|integer|exists:business_lines,id',
            'bot_name' => 'required|string|max:80',
            'greeting_message' => 'nullable|string|max:500',
            'handoff_keywords' => 'nullable|string|max:255',
            'allowed_origin' => 'nullable|url|max:255',
            'is_live' => 'required|boolean',
        ]);

        // Normalize to just scheme+host — e.g. "https://aandbcleaner.org/some/page"
        // becomes "https://aandbcleaner.org", matching exactly what a
        // browser's Origin header actually sends (never a path).
        $allowedOrigin = null;
        if (!empty($data['allowed_origin'])) {
            $parts = parse_url($data['allowed_origin']);
            $allowedOrigin = isset($parts['scheme'], $parts['host'])
                ? $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : '')
                : null;
        }

        $stmt = Database::connection()->prepare(
            'INSERT INTO chatbot_settings (business_line_id, bot_name, greeting_message, handoff_keywords, allowed_origin, is_live, updated_by, updated_at)
             VALUES (:bl, :name, :greeting, :keywords, :origin, :live, :user, NOW())
             ON DUPLICATE KEY UPDATE bot_name = VALUES(bot_name), greeting_message = VALUES(greeting_message),
                handoff_keywords = VALUES(handoff_keywords), allowed_origin = VALUES(allowed_origin),
                is_live = VALUES(is_live), updated_by = VALUES(updated_by), updated_at = NOW()'
        );
        $stmt->execute([
            'bl' => $data['business_line_id'], 'name' => $data['bot_name'], 'greeting' => $data['greeting_message'] ?? null,
            'keywords' => $data['handoff_keywords'] ?? null, 'origin' => $allowedOrigin,
            'live' => $data['is_live'] ? 1 : 0, 'user' => $this->currentUserId(),
        ]);

        ActivityLogger::logAction('Chatbot settings updated', 'admin');

        return AjaxResponse::success(null, 'Chatbot settings saved.');
    }
}