<?php

declare(strict_types=1);

namespace PloverCRM\Modules\Integrations\Services;

use PloverCRM\Modules\Integrations\Models\MetaConnection;

/**
 * Meta Connection Service
 * 
 * Manages Facebook page connections.
 */
class MetaConnectionService
{
    private const TABLE_NAME = 'plover_crm_meta_connections';
    private const CENTRAL_API = 'https://webplover.com/api/facebook';

    /**
     * Get all connections
     * 
     * @param bool $activeOnly Only return active connections
     * @return MetaConnection[]
     */
    public static function getAll(bool $activeOnly = false): array
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        $sql = "SELECT * FROM $table";
        if ($activeOnly) {
            $sql .= " WHERE status = 'active'";
        }
        $sql .= " ORDER BY page_name ASC";

        $rows = $wpdb->get_results($sql, ARRAY_A);

        if (!$rows) {
            return [];
        }

        return array_map(fn($row) => new MetaConnection($row), $rows);
    }

    /**
     * Get connection by ID
     */
    public static function getById(int $id): ?MetaConnection
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        $row = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table WHERE id = %d", $id),
            ARRAY_A
        );

        return $row ? new MetaConnection($row) : null;
    }

    /**
     * Get connection by page ID
     */
    public static function getByPageId(string $pageId): ?MetaConnection
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        $row = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table WHERE page_id = %s", $pageId),
            ARRAY_A
        );

        return $row ? new MetaConnection($row) : null;
    }

    /**
     * Check if page is already connected
     */
    public static function exists(string $pageId): bool
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        return (bool) $wpdb->get_var(
            $wpdb->prepare("SELECT 1 FROM $table WHERE page_id = %s LIMIT 1", $pageId)
        );
    }

    /**
     * Create new connection
     */
    public static function create(array $data): ?int
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        $result = $wpdb->insert($table, [
            'page_id' => sanitize_text_field($data['page_id']),
            'page_name' => sanitize_text_field($data['page_name']),
            'page_access_token' => sanitize_text_field($data['page_access_token']),
            'status' => $data['status'] ?? 'active',
            'connected_at' => time(),
            'updated_at' => time(),
        ], ['%s', '%s', '%s', '%s', '%d', '%d']);

        if (!$result) {
            return null;
        }

        // Clear cache
        delete_transient('plover_crm_meta_forms');

        return (int) $wpdb->insert_id;
    }

    /**
     * Update connection
     */
    public static function update(int $id, array $data): bool
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        $update = [];
        $formats = [];

        if (isset($data['page_name'])) {
            $update['page_name'] = sanitize_text_field($data['page_name']);
            $formats[] = '%s';
        }
        if (isset($data['page_access_token'])) {
            $update['page_access_token'] = sanitize_text_field($data['page_access_token']);
            $formats[] = '%s';
        }
        if (isset($data['status'])) {
            $update['status'] = $data['status'];
            $formats[] = '%s';
        }

        if (empty($update)) {
            return false;
        }

        $update['updated_at'] = time();
        $formats[] = '%d';

        $result = $wpdb->update($table, $update, ['id' => $id], $formats, ['%d']);

        delete_transient('plover_crm_meta_forms');

        return $result !== false;
    }

    /**
     * Delete connection
     */
    public static function delete(int $id): bool
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;

        $connection = self::getById($id);
        if (!$connection) {
            return false;
        }

        // Unregister from central server first
        self::unregisterFromCentral($connection->pageId);

        $result = $wpdb->delete($table, ['id' => $id], ['%d']);

        delete_transient('plover_crm_meta_forms');

        return $result !== false;
    }

    /**
     * Register page with central webhook server
     */
    public static function registerWithCentral(string $pageId, string $siteUrl): bool
    {
        $response = wp_remote_post(self::CENTRAL_API . '/register-webhook.php', [
            'body' => json_encode([
                'page_id' => $pageId,
                'site_url' => $siteUrl,
            ]),
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'timeout' => 10,
        ]);

        if (is_wp_error($response)) {
            error_log('[Meta] Central register failed: ' . $response->get_error_message());
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);
        return $code === 200;
    }

    /**
     * Unregister page from central webhook server
     */
    private static function unregisterFromCentral(string $pageId): void
    {
        wp_remote_post(self::CENTRAL_API . '/unregister-webhook.php', [
            'body' => json_encode(['page_id' => $pageId]),
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'timeout' => 10,
        ]);
    }

    /**
     * Install database table
     */
    public static function install(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . self::TABLE_NAME;
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            page_id varchar(100) NOT NULL,
            page_name varchar(255) NOT NULL,
            page_access_token text NOT NULL,
            status varchar(20) NOT NULL DEFAULT 'active',
            connected_at bigint(20) unsigned NOT NULL,
            updated_at bigint(20) unsigned NOT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY page_id (page_id),
            KEY status (status)
        ) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }
}
