<?php
/**
 * 📝 TEXT OVERRIDES CONTROLLER - V2.2 INTEGRATED
 *
 * Handles text customization for en_US (no translation overhead)
* Uses DATABASE TABLE wp_fleekdash_text_overrides for maximum performance
* Integrated with existing I18nManager system
 *
 * @package FleekDash\Controllers
 * @since 2.2.0
 */

namespace FleekDash\Controllers;

use WP_REST_Request;
use FleekDash\Services\ResponseService;
use FleekDash\Core\I18nManager;

class TextOverridesController
{
    /**
     * Get all text overrides for a locale (from database table)
     */
    public function getOverrides(WP_REST_Request $request)
    {
        try {
            $locale = $request->get_param('locale');

            if (!$locale) {
                return ResponseService::error('Locale is required', [], 400);
            }

            // V2.2 INTEGRATED: Use database table
            global $wpdb;
            $table_name = $wpdb->prefix . 'fleekdash_text_overrides';

            $results = $wpdb->get_results($wpdb->prepare(
                "SELECT original_text, custom_text FROM {$table_name} WHERE locale = %s",
                $locale
            ), ARRAY_A);

            $overrides = [];
            foreach ($results as $row) {
                $overrides[$row['original_text']] = $row['custom_text'];
            }

            return ResponseService::success('Text overrides retrieved', ['overrides' => $overrides]);
        } catch (\Exception $e) {
            return ResponseService::error('Failed to get overrides', ['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Get all available strings for customization
     *
* V2.2 INTEGRATED: Reads REAL PO files + database overrides
     */
    public function getAllStrings(WP_REST_Request $request)
    {
        $response = null;
        try {
            $locale = $request->get_param('locale');

            if (!$locale) {
                $response = ResponseService::error('Locale is required', [], 400);
            } else {
                $overrideMap = $this->getOverrideMap((string) $locale);
                $strings = $this->buildStringsForLocale((string) $locale, $overrideMap);
                $response = ResponseService::success('All strings retrieved', ['strings' => $strings]);
            }
        } catch (\Exception $e) {
            $response = ResponseService::error('Failed to get strings', ['error' => $e->getMessage()], 500);
        }

        return $response ?? ResponseService::error('Failed to get strings', [], 500);
    }

    /**
     * Parse PO file and extract strings using WordPress native parser
     *
     * @param string $poFile Path to PO file
     * @return array Array of strings with msgid/msgstr
     */
    private function parsePoFile(string $poFile): array
    {
        // Use WordPress native PO parser
        if (!class_exists('PO')) {
            require_once ABSPATH . WPINC . '/pomo/po.php';
        }

        $po = new \PO();
        if (!$po->import_from_file($poFile)) {
            return [];
        }

        $strings = [];
        foreach ($po->entries as $entry) {
            // Skip empty entries and headers
            if (empty($entry->singular) || $entry->singular === '') {
                continue;
            }

            $strings[] = [
                'msgid' => $entry->singular,
                'msgstr' => $entry->translations[0] ?? '',
            ];
        }

        return $strings;
    }

    /**
     * Generate string ID from msgid
     */
    private function generateStringId(string $msgid): string
    {
        $normalized = strtolower(preg_replace('/[^a-z0-9]+/', '-', $msgid) ?? '');
        $trimmed = trim($normalized, '-');
        $base = $trimmed !== '' ? $trimmed : 'str';
        $hash = substr(md5($msgid), 0, 8);
        return "{$base}-{$hash}";
    }

    /**
     * Update a single text override (in database table)
     */
    public function updateOverride(WP_REST_Request $request)
    {
        $response = null;
        try {
            $locale = $request->get_param('locale');
            $string_id = $request->get_param('string_id');
            $body = $request->get_json_params();
            $msgstr = $body['msgstr'] ?? '';
            $originalText = is_array($body) && isset($body['original_text']) && is_string($body['original_text'])
                ? $body['original_text']
                : (string) $string_id;

            if (!$locale || !$string_id) {
                $response = ResponseService::error('Locale and string ID are required', [], 400);
            } else {
                $this->persistOverride((string) $locale, $originalText, (string) $msgstr);

                // Clear I18nManager cache
                I18nManager::getInstance()->clearCache();

                $response = ResponseService::success('Override updated successfully');
            }
        } catch (\Exception $e) {
            $response = ResponseService::error('Failed to update override', ['error' => $e->getMessage()], 500);
        }

        return $response ?? ResponseService::error('Failed to update override', [], 500);
    }

    /**
     * Delete a text override (restore original) from database table
     */
    public function deleteOverride(WP_REST_Request $request)
    {
        $response = null;
        try {
            $locale = $request->get_param('locale');
            $string_id = $request->get_param('string_id');

            if (!$locale || !$string_id) {
                $response = ResponseService::error('Locale and string ID are required', [], 400);
            } else {
                $deleted = $this->deletePersistedOverride((string) $locale, (string) $string_id);
                if (!$deleted) {
                    $response = ResponseService::error('Override not found', [], 404);
                } else {
                    // Clear I18nManager cache
                    I18nManager::getInstance()->clearCache();
                    $response = ResponseService::success('Override deleted successfully');
                }
            }
        } catch (\Exception $e) {
            $response = ResponseService::error('Failed to delete override', ['error' => $e->getMessage()], 500);
        }

        return $response ?? ResponseService::error('Failed to delete override', [], 500);
    }

    /**
     * Get default strings for initialization
     */
    private function getDefaultStrings(): array
    {
        // Return common UI strings that users might want to customize
        return [
            ['id' => 'dashboard', 'msgid' => 'Dashboard'],
            ['id' => 'posts', 'msgid' => 'Posts'],
            ['id' => 'pages', 'msgid' => 'Pages'],
            ['id' => 'comments', 'msgid' => 'Comments'],
            ['id' => 'settings', 'msgid' => 'Settings'],
            ['id' => 'users', 'msgid' => 'Users'],
            ['id' => 'plugins', 'msgid' => 'Plugins'],
            ['id' => 'themes', 'msgid' => 'Themes'],
            ['id' => 'search', 'msgid' => 'Search'],
            ['id' => 'save', 'msgid' => 'Save'],
            ['id' => 'cancel', 'msgid' => 'Cancel'],
            ['id' => 'delete', 'msgid' => 'Delete'],
            ['id' => 'edit', 'msgid' => 'Edit'],
            ['id' => 'view', 'msgid' => 'View'],
            ['id' => 'add-new', 'msgid' => 'Add New'],
            ['id' => 'update', 'msgid' => 'Update'],
            ['id' => 'publish', 'msgid' => 'Publish'],
            ['id' => 'draft', 'msgid' => 'Draft'],
            ['id' => 'preview', 'msgid' => 'Preview'],
            ['id' => 'trash', 'msgid' => 'Trash'],
        ];
    }

    /**
     * @return array<string, string>
     */
    private function getOverrideMap(string $locale): array
    {
        global $wpdb;
        $tableName = $wpdb->prefix . 'fleekdash_text_overrides';
        $overrides = $wpdb->get_results($wpdb->prepare(
            "SELECT original_text, custom_text FROM {$tableName} WHERE locale = %s",
            $locale
        ), ARRAY_A);

        $overrideMap = [];
        foreach ($overrides as $row) {
            $overrideMap[$row['original_text']] = $row['custom_text'];
        }

        return $overrideMap;
    }

    /**
     * @param array<string, string> $overrideMap
     * @return array<int, array<string, mixed>>
     */
    private function buildStringsForLocale(string $locale, array $overrideMap): array
    {
        $poFile = $this->findPoFileForLocale($locale);
        $result = [];

        if ($poFile && $locale !== 'en_US') {
            $poStrings = $this->parsePoFile($poFile);
            $usedIds = [];
            foreach ($poStrings as $string) {
                $msgid = $string['msgid'];
                $hasOverride = isset($overrideMap[$msgid]);
                $id = $this->generateStringId($msgid);
                if (isset($usedIds[$id])) {
                    $usedIds[$id]++;
                    $id = "{$id}-{$usedIds[$id]}";
                } else {
                    $usedIds[$id] = 0;
                }
                $result[] = [
                    'id' => $id,
                    'msgid' => $msgid,
                    'msgstr' => $hasOverride ? $overrideMap[$msgid] : $string['msgstr'],
                    'translated' => $hasOverride || !empty($string['msgstr']),
                ];
            }

            return $result;
        }

        $defaultStrings = $this->getDefaultStrings();
        foreach ($defaultStrings as $string) {
            $msgid = $string['msgid'];
            $result[] = [
                'id' => $string['id'],
                'msgid' => $msgid,
                'msgstr' => $overrideMap[$msgid] ?? '',
                'translated' => isset($overrideMap[$msgid]) && !empty($overrideMap[$msgid]),
            ];
        }

        return $result;
    }

    private function findPoFileForLocale(string $locale): ?string
    {
        $searchPaths = [
            WP_CONTENT_DIR . "/languages/plugins/fleekdash/fleekdash-{$locale}.po",
            WP_CONTENT_DIR . "/languages/plugins/fleekdash-{$locale}.po",
        ];

        $poFile = null;
        foreach ($searchPaths as $path) {
            if (file_exists($path)) {
                $poFile = $path;
                break;
            }
        }

        return $poFile;
    }

    private function persistOverride(string $locale, string $stringId, string $msgstr): void
    {
        global $wpdb;
        $tableName = $wpdb->prefix . 'fleekdash_text_overrides';

        if ($msgstr === '') {
            $wpdb->delete(
                $tableName,
                [
                    'locale' => $locale,
                    'original_text' => $stringId,
                ],
                ['%s', '%s']
            );
            return;
        }

        $wpdb->replace(
            $tableName,
            [
                'locale' => $locale,
                'original_text' => $stringId,
                'custom_text' => $msgstr,
                'updated_at' => \current_time('mysql'),
            ],
            ['%s', '%s', '%s', '%s']
        );
    }

    private function deletePersistedOverride(string $locale, string $stringId): bool
    {
        global $wpdb;
        $tableName = $wpdb->prefix . 'fleekdash_text_overrides';
        $deleted = $wpdb->delete(
            $tableName,
            [
                'locale' => $locale,
                'original_text' => $stringId,
            ],
            ['%s', '%s']
        );

        return (bool) $deleted;
    }
}
