<?php 
if (!defined('ABSPATH')) exit;
global $flexyconsentSettings; $flexyconsentSettings = 'flexyconsent_settings';

add_action('admin_enqueue_scripts','flexyconsent_scripts');
function flexyconsent_scripts($hook) {
    $pages = [ 'toplevel_page_flexyconsent-startPage' ];
    global $flexyconsent_menu_title;
    global $flexyconsent_pages;
    global $flexyconsent_plugin_dir_url;
    foreach($flexyconsent_pages as $page) {
        $pages[] = sanitize_title($flexyconsent_menu_title) . '_page_flexyconsent-'.$page['id'];
    }

    $userMessages = array(
        '1' => esc_html__('You have a paid subscription and plan for next period.', 'flexyconsent'),
        '2' => esc_html__('You have a free subscription.', 'flexyconsent')
    );
    $responseMessages = array(
         '3' => esc_html__('Authentication failed!', 'flexyconsent'),
        '23' => esc_html__('You cannot close your account because you have a paid subscription and its current period will end on [endDate].<br>You can edit from [URL]', 'flexyconsent'),
        '24' => esc_html__('You cannot close your account because you have another project: [projectNames].<br>You can edit from [URL]', 'flexyconsent'),
        '25' => esc_html__('You cannot close your account because you have a project belonging to another service: [serviceNames].<br> You can edit from [URL]', 'flexyconsent')
    );
    
    $flexyconsentLocalizeData = array( 
        'nonce' => wp_create_nonce( 'wp_rest' ),
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'siteurl' => get_site_url(),
        'resturl' => get_rest_url(),
        'pluginDirUri' => $flexyconsent_plugin_dir_url,
        'redirectRoot' => admin_url( 'admin.php?page=flexyconsent-'),
        'redirectMainRoot' => admin_url( 'admin.php?page='),
        'endpoint' => 'https://flexyconsent.com/rest/',
        'email' => flexyconsent_getOption('email'),
        'apiKey' => flexyconsent_getOption('apiKey'),
        'projectId' => flexyconsent_getOption('projectId'),
        'projectScript' => flexyconsent_getOption('script'),
        'projectScriptSrc' => flexyconsent_getOption('scriptSrc'),
        'updateTime' => flexyconsent_getOption('updateTime'),
        'invoiceInfo' => esc_html__('Invoice Info', 'flexyconsent'),
        'nameOnInvoice' => esc_html__('Name On Invoice', 'flexyconsent'),
        'accountType' => esc_html__('Account Type', 'flexyconsent'),
        'businessAccount' => esc_html__('Business Account', 'flexyconsent'),
        'personalAccount' => esc_html__('Personal Account', 'flexyconsent'),
        'address' => esc_html__('Address', 'flexyconsent'),
        'city' => esc_html__('City', 'flexyconsent'),
        'country' => esc_html__('Country', 'flexyconsent'),
        'postcode' => esc_html__('Post Code', 'flexyconsent'),
        'vatnumber' => esc_html__('VAT Number', 'flexyconsent'),
        'wrongEmailAddress' => esc_html__('Your email address is wrong.', 'flexyconsent'),
        'enabledText' => esc_html__('Enabled', 'flexyconsent'),
        'disabledText' => esc_html__('Disabled (Consent window will not be displayed on your website)', 'flexyconsent'),

        'visitsNewClient' => esc_html__('New visitors', 'flexyconsent'),
        'visitsExistingClient' => esc_html__('Returning visitors', 'flexyconsent'),
        'visitsWithConsent' => esc_html__('Visits with consent', 'flexyconsent'),
        'visitsWithoutConsent' => esc_html__('Visits without consent', 'flexyconsent'),
        'visitsNoPreference' => esc_html__('Visits with no preference', 'flexyconsent'),
        'visitsTotal' => esc_html__('Total visitors', 'flexyconsent'),
        'pageViewsWithNoPreference' => esc_html__('Pageviews with no preference', 'flexyconsent'),
        'pageViewsWithConsent' => esc_html__('Pageviews with consent', 'flexyconsent'),
        'pageViewsWithoutConsent' => esc_html__('Pageviews without consent', 'flexyconsent'),
        'pageViewsTotal' => esc_html__('Total pageviews', 'flexyconsent'),
        'consentNotRequired' => esc_html__('Consent not required', 'flexyconsent'),
        'consentRequests' => esc_html__('Consent requested', 'flexyconsent'),
        'consentAccepts' => esc_html__('Accepted', 'flexyconsent'),
        'consentRejects' => esc_html__('Rejected', 'flexyconsent'),
        'consentPartiallyAccepts' => esc_html__('Partially accepted', 'flexyconsent'),

        'dashboard' => esc_html__('Dashboard', 'flexyconsent'),
        'subscription' => esc_html__('Subscription', 'flexyconsent'),
        'currentScreen' => get_current_screen(),
        'currentPlan' => esc_html__('Current Plan', 'flexyconsent'),
        'period' => esc_html__('Period', 'flexyconsent'),
        'websiteAlreadySelected' => esc_html__('You can only assign one website to one subscription!', 'flexyconsent'),
        'monthly' => esc_html__('Monthly', 'flexyconsent'),
        'annual' => esc_html__('Annual', 'flexyconsent'),
        'website' => esc_html__('Website', 'flexyconsent'),
        'select' => esc_html__('Select', 'flexyconsent'),
        'pageviewLimitMsgForDomain' => esc_html__('Your website [domain] has reached the monthly page view limit on the [planName] plan. To ensure uninterrupted service and accurate consent tracking, we recommend upgrading your plan.', 'flexyconsent'),
        'subscriptionPeriod' => esc_html__('Subscription period', 'flexyconsent'),
        'remainMonthCount' => esc_html__('Remaining time: [monthCount] month', 'flexyconsent'),
        'remainMonthsCount' => esc_html__('Remaining time: [monthCount] months', 'flexyconsent'),
        'remainDayCount' => esc_html__('Remaining time: [dayCount] day', 'flexyconsent'),
        'remainDaysCount' => esc_html__('Remaining time: [dayCount] days', 'flexyconsent'),
        'subscriptionCancelMessage' => esc_html__('Your subscription will be cancelled at the end of the period.', 'flexyconsent'),
        'subscriptionRenewMessage' => esc_html__('Your subscription will be renewed at the end of the period.', 'flexyconsent'),
        // 'subscriptionUpgradeMessage' => esc_html__('Your subscription will be upgraded to the [Next Type] package at the end of the period.', 'flexyconsent'),
        // 'subscriptionDowngradeMessage' => esc_html__('Your subscription will be downgraded to the [Next Type] package at the end of the period.', 'flexyconsent'),
        'planFeatures' => esc_html__('Plan Features', 'flexyconsent'),
        'cancelSubscription' => esc_html__('Cancel Subscription', 'flexyconsent'),
        // 'subscriptionTrialMessage' => esc_html__('Your subscription is on a trial period. After that, you will be on the [FreePlanName] plan. To access additional features, you will need to purchase a new plan.', 'flexyconsent'),
        'cancelling' => esc_html__('Cancelling...', 'flexyconsent'),
        'discountText' => esc_html__('[Number]% off', 'flexyconsent'),
        'freePlanDescription' => esc_html__('5,000 Pageviews/Month<br>Geo-Targeting<br>Single Language<br>E-mail Support<br>TCF 2.2 Support<br><del>Cookie Scanner</del><br><del>Auto Blocker</del><br><del>Google Consent Mode V2</del><br><del>API support</del>', 'flexyconsent'),
        'basicPlanDescription' => esc_html__('100,000 Pageviews/Month<br>Geo-Targeting<br>43 Languages Supported<br>E-mail &amp; Chat Support<br>TCF 2.2 Support<br>Cookie Scanner<br>Auto Blocker<br>Google Consent Mode V2<br>API support', 'flexyconsent'),
        'plusPlanDescription' => esc_html__('Unlimited Pageviews/Month<br>Geo-Targeting<br>43 Languages Supported<br>E-mail & Chat Support<br>TCF 2.2 Support<br>Cookie Scanner<br>Auto Blocker<br>Google Consent Mode V2<br>API support', 'flexyconsent'),
        'buy' => esc_html__('Buy', 'flexyconsent'),
        'contactUs' => esc_html__('Contact Us', 'flexyconsent'),
        'subscribe' => esc_html__('Subscribe', 'flexyconsent'),
        'subscribed' => esc_html__('Subscribed', 'flexyconsent'),
        'paymentPageNewPlanTitle' => esc_html__('Cancel current plan and subscribe to [PlanName] plan', 'flexyconsent'),
        'enabled' => flexyconsent_getOption('enabled'),
        'userMessages' => $userMessages,
        'responseMessages' => $responseMessages,
        'enterUserInfoMessage' => esc_html__('Please enter required information before subscribing.', 'flexyconsent'),

        'cookieList' => esc_html__('Cookie List', 'flexyconsent'),
        'addCookie' => esc_html__('Add Cookie', 'flexyconsent'),
        'refresh' => esc_html__('Refresh', 'flexyconsent'),
        'allTypes' => esc_html__('All Types', 'flexyconsent'),
        'essential' => esc_html__('Essential', 'flexyconsent'),
        'personalization' => esc_html__('Personalization', 'flexyconsent'),
        'analytics' => esc_html__('Analytics', 'flexyconsent'),
        'marketing' => esc_html__('Marketing', 'flexyconsent'),
        'security' => esc_html__('Security', 'flexyconsent'),
        'other' => esc_html__('Others', 'flexyconsent'),
        'displayName' => esc_html__('Display Name', 'flexyconsent'),
        'name' => esc_html__('Name', 'flexyconsent'),
        'type' => esc_html__('Type', 'flexyconsent'),
        'retentionPeriod' => esc_html__('Retention Period', 'flexyconsent'),
        'retentionPeriodNote' => esc_html__('Examples: Session, 30 days, 1 year, 2 years, etc.', 'flexyconsent'),
        'actions' => esc_html__('Actions', 'flexyconsent'),
        'cookieScanner' => esc_html__('Cookie Scanner', 'flexyconsent'),
        'automaticDetection' => esc_html__('Automatic Cookie Detection', 'flexyconsent'),
        'cookieScannerDescription' => esc_html__('Scan your website to automatically detect cookies and update your cookie list. Our advanced scanner analyzes your web pages and identifies all cookies being used, including tracking pixels, analytics cookies, and third-party integrations.', 'flexyconsent'),
        'firewallRequirement' => esc_html__('Firewall Setup Required:', 'flexyconsent'),
        'firewallNote' => esc_html__('Please add our cookie scanner IP addresses to the whitelist on your firewall to allow scanning.', 'flexyconsent'),
        'viewIpList' => esc_html__('View IP Addresses', 'flexyconsent'),
        'scanFeatures' => esc_html__('What Our Scanner Detects:', 'flexyconsent'),
        'essentialCookies' => esc_html__('Essential and functional cookies', 'flexyconsent'),
        'analyticsCookies' => esc_html__('Analytics and performance tracking', 'flexyconsent'),
        'marketingCookies' => esc_html__('Marketing and advertising cookies', 'flexyconsent'),
        'personalizationCookies' => esc_html__('Personalization and preference cookies', 'flexyconsent'),
        'thirdPartyCookies' => esc_html__('Third-party integrations and plugins', 'flexyconsent'),
        'scannerActions' => esc_html__('Scanner Actions', 'flexyconsent'),
        'startNewScan' => esc_html__('Start New Scan', 'flexyconsent'),
        'viewStatus' => esc_html__('View Status', 'flexyconsent'),
        'scanTime' => esc_html__('Typical scan time: 1-3 hours.', 'flexyconsent'),
        'noCookiesFound' => esc_html__('No cookies found', 'flexyconsent'),
        'cookiesFound' => esc_html__('Cookies Found', 'flexyconsent'),
        'cookieNames' => esc_html__('Cookie Names', 'flexyconsent'),
        'cookie' => esc_html__('cookie', 'flexyconsent'),
        'addCookieNote' => esc_html__('Click "Add Cookie" to create your first cookie entry', 'flexyconsent'),
        'ipListTitle' => esc_html__('Cookie Scanner IP Addresses', 'flexyconsent'),
        'ipListDescription' => esc_html__('Please add these IP addresses to your firewall whitelist to allow our cookie scanner to access your website:', 'flexyconsent'),
        'ipAddressesStr' => esc_html__('IP Addresses', 'flexyconsent'),
        'copyToClipboard' => esc_html__('Copy to Clipboard', 'flexyconsent'),
        'close' => esc_html__('Close', 'flexyconsent'),
        'configureScan' => esc_html__('Configure Scan', 'flexyconsent'),
        'scanModalDescription' => esc_html__('Enter the URL of the page you want to scan for cookies. Our scanner will analyze the page and detect all cookies being used.', 'flexyconsent'),
        'downloadPageUrl' => esc_html__('Download Page URL', 'flexyconsent'),
        'scanUrlHelper' => esc_html__('Enter the URL of the page you want to scan for cookies', 'flexyconsent'),
        'scanTip' => esc_html__('Tip:', 'flexyconsent'),
        'scanTipText' => esc_html__('For best results, scan your homepage or a page that loads all your tracking scripts and cookies.', 'flexyconsent'),
        'important' => esc_html__('Important', 'flexyconsent'),
        'importantTitle' => esc_html__('Important:', 'flexyconsent'),
        'firewallReminder' => esc_html__('Make sure our scanner IP addresses are whitelisted in your firewall', 'flexyconsent'),
        'cancel' => esc_html__('Cancel', 'flexyconsent'),
        'startScan' => esc_html__('Start Scan', 'flexyconsent'),
        'scanStatus' => esc_html__('Scan Status', 'flexyconsent'),
        'loadingStatus' => esc_html__('Loading scan status...', 'flexyconsent'),
        'noScansFound' => esc_html__('No scans found for this domain', 'flexyconsent'),
        'startFirstScan' => esc_html__('Start your first scan by entering a URL above', 'flexyconsent'),
        'scanHistory' => esc_html__('Scan History', 'flexyconsent'),
        'preview' => esc_html__('Preview', 'flexyconsent'),
        'url' => esc_html__('URL', 'flexyconsent'),
        'status' => esc_html__('Status', 'flexyconsent'),
        'created' => esc_html__('Created', 'flexyconsent'),
        'completed' => esc_html__('Completed', 'flexyconsent'),
        'actions' => esc_html__('Actions', 'flexyconsent'),
        'basicInformation' => esc_html__('Basic Information', 'flexyconsent'),
        'cookieNameRequired' => esc_html__('Cookie name is required', 'flexyconsent'),
        'displayName' => esc_html__('Display Name', 'flexyconsent'),
        'displayNamePlaceHolder' => esc_html__('e.g., Analytics Cookie (optional - defaults to name)', 'flexyconsent'),
        'displayNameNote' => esc_html__('If empty, will default to the cookie name', 'flexyconsent'),
        'selectType' => esc_html__('Select Type', 'flexyconsent'),
        'typeRequired' => esc_html__('Type is required', 'flexyconsent'),
        'descriptionPurpose' => esc_html__('Description and Purpose', 'flexyconsent'),
        'description' => esc_html__('Description', 'flexyconsent'),
        'descriptionLanguageNote' => esc_html__('Description will be saved for the selected language', 'flexyconsent'),
        'vendor' => esc_html__('Vendor', 'flexyconsent'),
        'privacyUrl' => esc_html__('Privacy URL', 'flexyconsent'),
        'technicalDetails' => esc_html__('Technical Details', 'flexyconsent'),
        'scriptUrl' => esc_html__('Script URL', 'flexyconsent'),
        'cookieScriptPlaceholder' => esc_html__('https://www.google-analytics.com/analytics.js', 'flexyconsent'),
        'cookieScriptNote' => esc_html__('If no script url provided, the cookie shouldn\'t be marked as essential.', 'flexyconsent'),
        'importantNote' => esc_html__('Avoid using your own website\'s URL as the Script URL, as it may disrupt your website\'s functionality.', 'flexyconsent'),
        'importantExample' => esc_html__('For example, if the third-party script that sets this cookie is:', 'flexyconsent'),
        'importantConclusion' => esc_html__('You should enter the Script URL pattern as:', 'flexyconsent'),
        'save' => esc_html__('Save', 'flexyconsent'),
        'fixErrorMessage' => esc_html__('<strong>Please fix the following errors:</strong><ul>', 'flexyconsent'),
        'copied' => esc_html__('Copied!', 'flexyconsent'),
        'cookieAddedSuccessfully' => esc_html__('Cookie added successfully!', 'flexyconsent'),
        'cookieUpdatedSuccessfully' => esc_html__('Cookie updated successfully!', 'flexyconsent'),
        'confirmDeleteCookie' => esc_html__('Are you sure you want to delete this cookie?', 'flexyconsent'),
        'cookieName' => esc_html__('Cookie Name', 'flexyconsent'),
        'cookieDeletedSuccessfully' => esc_html__('Cookie deleted successfully!', 'flexyconsent'),
        'cookieDetails' => esc_html__('Cookie Details:', 'flexyconsent'),
        'properties' => esc_html__('Properties', 'flexyconsent'),
        'custom' => esc_html__('Custom', 'flexyconsent'),
        'availableLanguages' => esc_html__('Available languages', 'flexyconsent'),
        'vendorInformation' => esc_html__('Vendor Information', 'flexyconsent'),
        'viewPolicy' => esc_html__('View Policy', 'flexyconsent'),
        'associatedScript' => esc_html__('Associated Script', 'flexyconsent'),
        'editCookie' => esc_html__('Edit Cookie', 'flexyconsent'),
        'pagePreview' => esc_html__('Page Preview', 'flexyconsent'),
        'scannedUrl' => esc_html__('Scanned URL', 'flexyconsent'),
        'openInNewTab' => esc_html__('Open in New Tab', 'flexyconsent'),
        'couldNotExtractURL' => esc_html__('Could not extract script URL', 'flexyconsent'),
        'previewUnavailable' => esc_html__('Preview Unavailable', 'flexyconsent'),
        'previewUnavailableDesc' => esc_html__('Unable to load the script in preview mode due to CORS restrictions.', 'flexyconsent'),
        'yourScript' => esc_html__('Your Script', 'flexyconsent'),
        'yourScriptCodeTitle' => esc_html__('Your Script Code:', 'flexyconsent'),
        'scriptWorksOnWebsite' => esc_html__('The script will work perfectly when implemented on your website. This preview limitation doesn\'t affect the actual functionality.', 'flexyconsent'),
        'scriptReadyToUse' => esc_html__('Your cookie declaration script is ready to use.', 'flexyconsent'),
        'scriptDisplaysTablesDesc' => esc_html__('When implemented on your website, this script will automatically display your cookie declaration tables.', 'flexyconsent'),
        'loadingPreview' => esc_html__('Loading preview...', 'flexyconsent'),
        'loadingPreviewDesc' => esc_html__('Loading cookie declaration preview...', 'flexyconsent'),
        'cookieDeclarationScript' => esc_html__('Cookie Declaration Script', 'flexyconsent'),
        'generateScriptForWebsite' => esc_html__('Generate Script for Your Website', 'flexyconsent'),
        'declarationScriptDescription' => esc_html__('Generate a script tag that displays your cookie declaration tables on your website. This helps you comply with GDPR, CCPA, and other privacy regulations by providing transparent information about all cookies used on your site.', 'flexyconsent'),
        'scriptFeatures' => esc_html__('Script Features:', 'flexyconsent'),
        'scriptFeature1' => esc_html__('Automatically organized cookie tables by category', 'flexyconsent'),
        'scriptFeature2' => esc_html__('Mobile-responsive design', 'flexyconsent'),
        'scriptFeature3' => esc_html__('Auto-updates when you modify cookies', 'flexyconsent'),
        'scriptFeature4' => esc_html__('GDPR and CCPA compliant formatting', 'flexyconsent'),
        'scriptFeature5' => esc_html__('Ready to link from your privacy policy', 'flexyconsent'),
        'scriptActions' => esc_html__('Script Actions', 'flexyconsent'),
        'previewDeclaration' => esc_html__('Preview Declaration', 'flexyconsent'),
        'viewInformation' => esc_html__('View Information', 'flexyconsent'),
        'oneTimeSetup' => esc_html__('One-time setup, automatic updates.', 'flexyconsent'),
        'loading' => esc_html__('Loading...', 'flexyconsent'),
        'loadingScript' => esc_html__('Loading script...', 'flexyconsent'),
        'noDomainSelected' => esc_html__('No domain selected', 'flexyconsent'),
        'noProjectsAvailable' => esc_html__('No projects available', 'flexyconsent'),
        'projectNotFound' => esc_html__('Project not found for selected domain', 'flexyconsent'),
        'failedToLoadScript' => esc_html__('Failed to load script', 'flexyconsent'),
        'error' => esc_html__('Error', 'flexyconsent'),
        'scriptTagForWebsite' => esc_html__('Script Tag for Your Website', 'flexyconsent'),
        'copyScript' => esc_html__('Copy Script', 'flexyconsent'),
        'copyScriptTag' => esc_html__('Copy Script Tag', 'flexyconsent'),
        'simpleIntegration' => esc_html__('Simple Integration', 'flexyconsent'),
        'simpleIntegrationDesc' => esc_html__('Just copy this single script tag and paste it into your website\'s HTML head section. This will automatically generate the cookie declaration tables on your page.', 'flexyconsent'),
        'htmlScriptTag' => esc_html__('HTML Script Tag', 'flexyconsent'),
        'howToAddToWebsite' => esc_html__('How to Add to Your Website', 'flexyconsent'),
        'option1AddToHead' => esc_html__('Option 1 - Add to HTML Head', 'flexyconsent'),
        'option2AddToPage' => esc_html__('Option 2 - Add to Specific Page', 'flexyconsent'),
        'scriptSecurityDesc' => esc_html__('This script is hosted securely and will automatically display your current cookie configuration. It updates automatically when you modify cookies in this manager.', 'flexyconsent'),
        'scriptCopied' => esc_html__('Script copied to clipboard!', 'flexyconsent'),
        'whyNeedThis' => esc_html__('Why Do You Need This?', 'flexyconsent'),
        'legalComplianceDesc' => esc_html__('Legal compliance regulations like GDPR, CCPA, and other privacy laws require websites to provide transparent information about all cookies they use. This script generates a professional cookie declaration tables that:', 'flexyconsent'),
        'listAllCookies' => esc_html__('Lists all cookies used on your website in organized tables', 'flexyconsent'),
        'showCookiePurposes' => esc_html__('Shows cookie purposes, retention periods, and providers', 'flexyconsent'),
        'helpComplyTransparency' => esc_html__('Helps you comply with transparency requirements', 'flexyconsent'),
        'linkFromPrivacyPolicy' => esc_html__('Can be linked from your privacy policy or cookie policy', 'flexyconsent'),
        'updatesAutomatically' => esc_html__('Updates automatically as you modify your cookie configuration', 'flexyconsent'),
        'howToAddDeclaration' => esc_html__('How to Add Cookie Declaration to Your Website', 'flexyconsent'),
        'step1CopyScript' => esc_html__('Step 1: Copy the Script Tag', 'flexyconsent'),
        'step1Desc' => esc_html__('Copy the script tag from the "Script Code" tab. This is a simple one-line HTML tag that you\'ll add to your website.', 'flexyconsent'),
        'step2AddToHTML' => esc_html__('Step 2: Add to Your Website\'s HTML', 'flexyconsent'),
        'step2Desc' => esc_html__('Paste the script tag into your Cookie Declaration HTML where you want the tables to appear:', 'flexyconsent'),
        'step3LinkFromPolicy' => esc_html__('Step 3: Link from Your Privacy Policy', 'flexyconsent'),
        'step3Desc' => esc_html__('Add a link to your cookie declaration page from your privacy policy, cookie policy, or website footer:', 'flexyconsent'),
        'step4AutoUpdates' => esc_html__('Step 4: Automatic Updates', 'flexyconsent'),
        'step4Desc' => esc_html__('The script automatically updates when you modify your cookie configuration in this manager. No need to manually update your website - it stays current automatically!', 'flexyconsent'),
        'legalComplianceBenefits' => esc_html__('Legal Compliance Benefits', 'flexyconsent'),
        'gdprCompliance' => esc_html__('GDPR Article 13 compliance', 'flexyconsent'),
        'ccpaCompliance' => esc_html__('CCPA transparency requirements', 'flexyconsent'),
        'cookieLawCompliance' => esc_html__('Cookie law disclosure obligations', 'flexyconsent'),
        'isoCompliance' => esc_html__('ISO 27001 documentation standards', 'flexyconsent'),
        'features' => esc_html__('Features', 'flexyconsent'),
        'mobileResponsive' => esc_html__('Mobile responsive design', 'flexyconsent'),
        'professionalStyling' => esc_html__('Professional styling', 'flexyconsent'),
        'organizedByCategories' => esc_html__('Organized by categories', 'flexyconsent'),
        'privacyPolicyLinks' => esc_html__('Privacy policy links', 'flexyconsent'),
        'autoUpdatesWithChanges' => esc_html__('Auto-updates with changes', 'flexyconsent'),
        'scriptGeneratesTablesDesc' => esc_html__('This script generates tables based on your current cookie configuration.', 'flexyconsent'),
        'userFriendly' => esc_html__('User-Friendly', 'flexyconsent'),
        'userFriendlyDesc' => esc_html__('Your website visitors will see a clean, organized tables showing exactly what cookies your site uses and why - building trust and meeting legal requirements.', 'flexyconsent'),
        'noScriptToCopy' => esc_html__('No script to copy', 'flexyconsent'),
        'livePreviewTitle' => esc_html__('Live Preview - Exactly How It Will Look on Your Website', 'flexyconsent'),
        'livePreviewDesc' => esc_html__('This preview shows exactly how the cookie declaration will appear on your website when visitors access it. The tables below contain your current cookie configuration and will update automatically when you modify your cookies in this manager.', 'flexyconsent'),
        'closePreview' => esc_html__('Close Preview', 'flexyconsent'),
        'previewNote' => esc_html__('Preview Note', 'flexyconsent'),
        'readyToUse' => esc_html__('Ready to Use', 'flexyconsent'),
        'readyToUseDesc' => esc_html__('This is exactly what your website visitors will see when they visit your cookie declaration page. The script automatically organizes your cookies by category (Essential, Analytics, Marketing, etc.) and displays all the required information for legal compliance.', 'flexyconsent'),
        'previewLimitations' => esc_html__('Preview Limitations', 'flexyconsent'),
        'previewCannotBeDisplayed' => esc_html__('The preview cannot be displayed due to browser security restrictions, but your script is ready and will work perfectly on your website.', 'flexyconsent'),
        'yourGeneratedScript' => esc_html__('Your Generated Script', 'flexyconsent'),
        'browserSecurityFeature' => esc_html__('This is a browser security feature and doesn\'t affect the actual functionality.', 'flexyconsent'),
    );
    

    wp_enqueue_script( 'flexyconsent-script-global', plugins_url('/js/flexyconsent-global.js', __FILE__ ));
    wp_localize_script( 'flexyconsent-script-global', 'flexyconsentData', $flexyconsentLocalizeData);

    if(!in_array($hook,$pages)) {
        wp_enqueue_style( 'flexyconsent-style-global', plugins_url( '/css/flexyconsent-global.css', __FILE__ ));
        return;
    }

    wp_enqueue_script( 'jquery-validation',  plugins_url('js/jquery.validate.min.js', __FILE__ ), array('jquery'), '1.21.0', true);
    wp_enqueue_script( 'jquery-validation-additional-methods', plugins_url('js/additional-methods.min.js', __FILE__ ), array('jquery-validation'), '1.21.0', true);
    wp_enqueue_script( 'flexyconsent-script', plugins_url('/js/flexyconsent.js', __FILE__ ));
    wp_enqueue_style( 'flexyconsent-style', plugins_url( '/css/flexyconsent.css', __FILE__ ));
    wp_enqueue_script( 'bootstrap', plugins_url('/plugins/bootstrap/js/bootstrap.min.js', __FILE__ ), array(), '5.1.3', true);
    wp_enqueue_script( 'bootstrap-bundle', plugins_url('/plugins/bootstrap/js/bootstrap.bundle.min.js', __FILE__ ), array(), '5.1.3', true);
    wp_enqueue_style( 'bootstrap', plugins_url('/plugins/bootstrap/css/bootstrap.min.css', __FILE__ ), array(), '5.1.3');
    wp_enqueue_style( 'fontawesome', plugins_url('/plugins/fontawesome/css/all.min.css', __FILE__ ), array(), '6.7.2');
    wp_localize_script( 'flexyconsent-script', 'flexyconsentData', $flexyconsentLocalizeData);
}

// Helpers
function flexyconsent_get_top_section() {
    global $flexyconsent_plugin_dir_url;
    echo wp_kses('<div class="d-flex justify-content-center align-items-center"><img src="'.esc_url($flexyconsent_plugin_dir_url).'images/flexyconsent.png" height="64" alt="FlexyConsent"><h1 class="ms-3">FlexyConsent</h1></div>', 
    ['div' => ['class' => []], 'img'=>[ 'src' => [], 'height'=> [], 'alt' => [] ], 'h1' => []]);

    echo wp_kses('<div id="flexyconsent-result-top" class="alert d-none" role="alert"></div>',['div' => ['id'=> [], 'class'=> [] ]]);
}

function flexyconsent_get_bottom_section(){
    echo wp_kses('<div id="flexyconsent-result" class="alert" role="alert"></div>',['div' => ['id'=> [], 'class'=> [] ]]);
}

function flexyconsent_getPageName($pageNameMain) {
    return '_'.$pageNameMain;
}

function flexyconsent_getSectionName($pageNameMain) {
    return 'flexyconsent_'.$pageNameMain.'_section';
}

function flexyconsent_goPage($pageCmp) {
    wp_redirect( esc_url(admin_url( 'admin.php?page=flexyconsent-'.$pageCmp )) );
    exit();
}
function flexyconsent_generateGoPage($pageCmp) {
    return esc_url(admin_url( 'admin.php?page=flexyconsent-'.$pageCmp ));
}
function flexyconsent_generateGoMainPage($pageCmp) {
    return esc_url(admin_url( 'admin.php?page='.$pageCmp ));
}

// function flexyconsent_getOption($pageName) {
//     return get_option( 'flexyconsent_settings_'.$pageName );
// }
function flexyconsent_getOption($key) {
    // return get_option( 'flexyconsent_settings' )[$key];
    global $flexyconsentSettings;
    return get_option( $flexyconsentSettings )[$key];
}

function flexyconsent_reset_options() {
    global $flexyconsentSettings;
    update_option( $flexyconsentSettings, [] );
}

// Rest
add_action( 'rest_api_init', function () {
    register_rest_route( 'flexyconsent/v1', '/option', array(
      'methods' => 'POST',
      'callback' => 'flexyconsent_update_option',
      'permission_callback' => function (WP_REST_Request $request) {
        return (wp_verify_nonce( $request->get_header('X-WP-Nonce'),'wp_rest') && current_user_can( 'manage_options' ));
       }
    ) );
} );

function flexyconsent_update_option(WP_REST_Request $request ) {
    // $option_name = 'flexyconsent_settings';
    global $flexyconsentSettings;
    $parameters = $request->get_body_params();
    if($parameters) {
        foreach($parameters['updates'] as $update) {
            $currentOption = get_option($flexyconsentSettings);
            $value = (isset($update['decrypted'])) ? base64_decode($update['value']) : $update['value'];
            $currentOption[$update['key']] = $value;
            update_option($flexyconsentSettings, $currentOption);
        }
        $data = ['status' =>'Success'];
        $response = new WP_REST_Response( $data );
        $response->set_status( 200 );
        return $response;
    } else {
        return true;
    }
}

// Include Cmp Script
add_action ( 'wp_head', 'flexyconsent_inHeader', -1000);
function flexyconsent_inHeader() {
    $enabled = flexyconsent_getOption("enabled");    
    if ($enabled === 'true' && flexyconsent_getOption("scriptSrc")) {        
        $script_src = flexyconsent_getOption("scriptSrc");
        wp_register_script('flexyconsent-script', $script_src, [], null, true);
        wp_enqueue_script('flexyconsent-script');
    }   
}


function flexyconsent_logout() {
    flexyconsent_reset_options();
    return flexyconsent_generateGoPage('startPage');
}