<?php
/**
 * DBA Startup Hub Registry — Central configuration engine
 *
 * ═══════════════════════════════════════════════════════════════════════
 *  Single source of truth for all Startup Hub settings, cities,
 *  categories (technology verticals), and CTA configuration.
 *
 *  ZERO CONFLICT with core Damalion, GeoBot, NewsBot, LuxStrat, LATAM:
 *    - Option keys:   dba_startup_hub_settings, dba_startup_hub_last_run
 *    - Meta keys:     _dba_startup_hub_auto_created, _dba_startup_hub_city, etc.
 *    - Cron hooks:    dba_startup_hub_daily_generation
 *    - Transients:    dba_startup_hub_generation_progress
 *    - Admin page:    dba-startup-hub
 *
 * @since 2.16.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_Startup_Hub_Registry {

    /* =================================================================
     *  MODULE CONFIG
     * ================================================================= */

    /**
     * Return the module-wide configuration constants.
     *
     * @return array
     */
    public static function get_config() {
        return array(
            'key'                  => 'startup_hub',
            'label'                => '🚀 U.S. Startup Hub',
            'menu_label'           => '🚀 Startup Hub',
            'admin_slug'           => 'dba-startup-hub',
            'settings_option'      => 'dba_startup_hub_settings',
            'last_run_option'      => 'dba_startup_hub_last_run',
            'hub_page_option'      => 'dba_startup_hub_hub_page_id',
            'meta_auto_created'    => '_dba_startup_hub_auto_created',
            'default_posts_per_run'=> 2,
            'timezone'             => 'America/New_York',
            'cron_hook'            => 'dba_startup_hub_daily_generation',
            'language'             => 'en',
        );
    }

    /* =================================================================
     *  CITIES
     * ================================================================= */

    /**
     * Get the list of active cities.
     * Falls back to defaults if no custom list has been saved.
     *
     * @return array
     */
    public static function get_cities() {
        $saved = get_option( 'dba_startup_hub_cities', array() );
        if ( ! empty( $saved ) && is_array( $saved ) ) {
            return $saved;
        }
        return self::get_default_cities();
    }

    /**
     * Default U.S. startup hub cities.
     *
     * Each entry: city, state, ecosystem label, weight (higher = more frequent).
     *
     * @return array
     */
    public static function get_default_cities() {
        return array(
            array( 'city' => 'San Francisco',   'state' => 'California',     'ecosystem' => 'Silicon Valley / SF Bay Area',          'weight' => 5 ),
            array( 'city' => 'New York',         'state' => 'New York',       'ecosystem' => 'NYC Tech & FinTech Hub',                'weight' => 5 ),
            array( 'city' => 'Austin',           'state' => 'Texas',          'ecosystem' => 'Austin Innovation Corridor',            'weight' => 4 ),
            array( 'city' => 'Boston',           'state' => 'Massachusetts',  'ecosystem' => 'Boston / Cambridge BioTech & AI Hub',   'weight' => 4 ),
            array( 'city' => 'Los Angeles',      'state' => 'California',     'ecosystem' => 'LA Tech, Media & Entertainment',        'weight' => 4 ),
            array( 'city' => 'Miami',            'state' => 'Florida',        'ecosystem' => 'Miami Tech / LatAm Gateway',            'weight' => 3 ),
            array( 'city' => 'Seattle',          'state' => 'Washington',     'ecosystem' => 'Seattle Cloud & Enterprise Tech',       'weight' => 3 ),
            array( 'city' => 'Chicago',          'state' => 'Illinois',       'ecosystem' => 'Chicago FinTech & SaaS',                'weight' => 3 ),
            array( 'city' => 'Denver',           'state' => 'Colorado',       'ecosystem' => 'Denver / Boulder Tech Corridor',        'weight' => 2 ),
            array( 'city' => 'Atlanta',          'state' => 'Georgia',        'ecosystem' => 'Atlanta FinTech & Cybersecurity',       'weight' => 2 ),
            array( 'city' => 'San Diego',        'state' => 'California',     'ecosystem' => 'San Diego BioTech & Defense Tech',      'weight' => 2 ),
            array( 'city' => 'Dallas',           'state' => 'Texas',          'ecosystem' => 'Dallas / DFW Enterprise Tech',          'weight' => 2 ),
            array( 'city' => 'Raleigh',          'state' => 'North Carolina', 'ecosystem' => 'Research Triangle Tech Hub',            'weight' => 2 ),
            array( 'city' => 'Pittsburgh',       'state' => 'Pennsylvania',   'ecosystem' => 'Pittsburgh Robotics & AI',              'weight' => 1 ),
            array( 'city' => 'Nashville',        'state' => 'Tennessee',      'ecosystem' => 'Nashville HealthTech',                  'weight' => 1 ),
            array( 'city' => 'Salt Lake City',   'state' => 'Utah',           'ecosystem' => 'Silicon Slopes SaaS Hub',               'weight' => 2 ),
            array( 'city' => 'Washington D.C.',  'state' => 'District of Columbia', 'ecosystem' => 'D.C. GovTech & Cybersecurity',    'weight' => 2 ),
            array( 'city' => 'Minneapolis',      'state' => 'Minnesota',      'ecosystem' => 'Minneapolis HealthTech & MedTech',      'weight' => 1 ),
            array( 'city' => 'Philadelphia',     'state' => 'Pennsylvania',   'ecosystem' => 'Philadelphia BioTech & EdTech',         'weight' => 1 ),
            array( 'city' => 'Portland',         'state' => 'Oregon',         'ecosystem' => 'Portland Open-Source & CleanTech',      'weight' => 1 ),
        );
    }

    /**
     * Pick a city using weighted random selection, avoiding recently used ones.
     *
     * @param  array $exclude_cities City names to skip.
     * @return array City entry.
     */
    public static function pick_city( array $exclude_cities = array() ) {
        $cities    = self::get_cities();
        $available = array();

        foreach ( $cities as $city ) {
            if ( in_array( $city['city'], $exclude_cities, true ) ) continue;
            $available[] = $city;
        }

        // If all excluded, reset and use full list
        if ( empty( $available ) ) {
            $available = $cities;
        }

        // Weighted selection
        $pool = array();
        foreach ( $available as $idx => $city ) {
            $weight = max( 1, intval( $city['weight'] ?? 1 ) );
            for ( $w = 0; $w < $weight; $w++ ) {
                $pool[] = $idx;
            }
        }

        $pick = $pool[ array_rand( $pool ) ];
        return $available[ $pick ];
    }

    /* =================================================================
     *  CATEGORIES (Technology Verticals)
     * ================================================================= */

    /**
     * Get all startup technology verticals / categories.
     *
     * Each category has: slug, short, name, keywords, damalion_angle.
     *
     * @return array
     */
    public static function get_categories() {
        return array(
            array(
                'slug'           => 'fintech',
                'short'          => 'FinTech',
                'name'           => 'Financial Technology (FinTech)',
                'keywords'       => array( 'FinTech', 'digital payments', 'neobank', 'blockchain finance', 'DeFi', 'regtech' ),
                'damalion_angle' => 'Damalion assists international investors and FinTech founders with corporate structuring, regulatory compliance, and cross-border licensing in the U.S. market.',
            ),
            array(
                'slug'           => 'ai-ml',
                'short'          => 'AI / ML',
                'name'           => 'Artificial Intelligence & Machine Learning',
                'keywords'       => array( 'AI startups', 'machine learning', 'generative AI', 'LLM', 'computer vision', 'NLP', 'AI infrastructure' ),
                'damalion_angle' => 'Damalion supports AI entrepreneurs with U.S. entity formation, IP protection strategies, and investor structuring for AI-focused ventures.',
            ),
            array(
                'slug'           => 'saas',
                'short'          => 'SaaS',
                'name'           => 'Software as a Service (SaaS)',
                'keywords'       => array( 'SaaS', 'cloud software', 'B2B SaaS', 'vertical SaaS', 'subscription model', 'PLG' ),
                'damalion_angle' => 'Damalion helps SaaS founders navigate U.S. incorporation, revenue recognition frameworks, and international expansion structuring.',
            ),
            array(
                'slug'           => 'biotech',
                'short'          => 'BioTech',
                'name'           => 'Biotechnology & Life Sciences',
                'keywords'       => array( 'biotech', 'life sciences', 'pharma startup', 'drug discovery', 'genomics', 'clinical trials' ),
                'damalion_angle' => 'Damalion advises biotech ventures on FDA-related structuring, clinical-stage financing, and cross-border IP licensing.',
            ),
            array(
                'slug'           => 'cleantech',
                'short'          => 'CleanTech',
                'name'           => 'Clean Technology & Climate Tech',
                'keywords'       => array( 'cleantech', 'climate tech', 'renewable energy', 'carbon capture', 'ESG', 'green hydrogen' ),
                'damalion_angle' => 'Damalion supports CleanTech founders with U.S. project structuring, IRA incentive optimization, and ESG compliance advisory.',
            ),
            array(
                'slug'           => 'healthtech',
                'short'          => 'HealthTech',
                'name'           => 'Health Technology & Digital Health',
                'keywords'       => array( 'healthtech', 'digital health', 'telemedicine', 'remote patient monitoring', 'health AI', 'EHR' ),
                'damalion_angle' => 'Damalion assists HealthTech entrepreneurs with HIPAA-compliant structuring, FDA digital health pathways, and U.S. market entry.',
            ),
            array(
                'slug'           => 'cybersecurity',
                'short'          => 'Cybersecurity',
                'name'           => 'Cybersecurity & Information Security',
                'keywords'       => array( 'cybersecurity', 'infosec', 'zero trust', 'threat detection', 'SIEM', 'identity management' ),
                'damalion_angle' => 'Damalion guides cybersecurity startups through U.S. government procurement structuring, CMMC compliance, and defense contractor registration.',
            ),
            array(
                'slug'           => 'edtech',
                'short'          => 'EdTech',
                'name'           => 'Education Technology',
                'keywords'       => array( 'EdTech', 'online learning', 'LMS', 'skills marketplace', 'corporate training', 'AI tutoring' ),
                'damalion_angle' => 'Damalion helps EdTech founders with U.S. entity formation, B2B/B2G procurement access, and international student data compliance.',
            ),
            array(
                'slug'           => 'proptech',
                'short'          => 'PropTech',
                'name'           => 'Property Technology & Real Estate Tech',
                'keywords'       => array( 'proptech', 'real estate tech', 'property management', 'iBuyer', 'construction tech', 'smart buildings' ),
                'damalion_angle' => 'Damalion advises PropTech ventures on U.S. real estate structuring, REIT compliance, and cross-border investment vehicles.',
            ),
            array(
                'slug'           => 'web3',
                'short'          => 'Web3',
                'name'           => 'Web3, Blockchain & Crypto',
                'keywords'       => array( 'Web3', 'blockchain', 'crypto', 'DeFi', 'NFT infrastructure', 'tokenization', 'DAO' ),
                'damalion_angle' => 'Damalion helps Web3 founders with U.S. regulatory structuring, SEC/CFTC compliance pathways, and token issuance frameworks.',
            ),
            array(
                'slug'           => 'robotics',
                'short'          => 'Robotics',
                'name'           => 'Robotics & Automation',
                'keywords'       => array( 'robotics', 'automation', 'autonomous vehicles', 'drone tech', 'industrial robots', 'warehouse automation' ),
                'damalion_angle' => 'Damalion supports robotics startups with U.S. IP protection, defense and industrial procurement access, and international expansion structuring.',
            ),
            array(
                'slug'           => 'spacetech',
                'short'          => 'SpaceTech',
                'name'           => 'Space Technology & Aerospace',
                'keywords'       => array( 'spacetech', 'satellite', 'launch services', 'space infrastructure', 'earth observation', 'aerospace startup' ),
                'damalion_angle' => 'Damalion guides SpaceTech ventures through ITAR/EAR compliance, FAA licensing, and U.S. government contracting frameworks.',
            ),
            array(
                'slug'           => 'foodtech',
                'short'          => 'FoodTech',
                'name'           => 'Food Technology & AgriTech',
                'keywords'       => array( 'foodtech', 'agritech', 'alternative protein', 'vertical farming', 'food delivery tech', 'precision agriculture' ),
                'damalion_angle' => 'Damalion assists FoodTech founders with FDA/USDA regulatory structuring, CPG distribution partnerships, and U.S. market entry.',
            ),
            array(
                'slug'           => 'insurtech',
                'short'          => 'InsurTech',
                'name'           => 'Insurance Technology',
                'keywords'       => array( 'insurtech', 'insurance AI', 'parametric insurance', 'claims automation', 'embedded insurance', 'underwriting tech' ),
                'damalion_angle' => 'Damalion helps InsurTech startups navigate state-level insurance licensing, MGA structuring, and cross-border reinsurance frameworks.',
            ),
            array(
                'slug'           => 'legaltech',
                'short'          => 'LegalTech',
                'name'           => 'Legal Technology',
                'keywords'       => array( 'legaltech', 'legal AI', 'contract automation', 'eDiscovery', 'compliance tech', 'legal marketplace' ),
                'damalion_angle' => 'Damalion supports LegalTech founders with U.S. professional services structuring, bar association compliance, and IP protection strategies.',
            ),
        );
    }

    /**
     * Pick a category using round-robin, avoiding recently used ones.
     *
     * @param  array $exclude_slugs Category slugs to skip.
     * @return array Category entry.
     */
    public static function pick_category( array $exclude_slugs = array() ) {
        $categories = self::get_categories();
        $available  = array();

        foreach ( $categories as $cat ) {
            if ( in_array( $cat['slug'], $exclude_slugs, true ) ) continue;
            $available[] = $cat;
        }

        // If all excluded, reset and use full list
        if ( empty( $available ) ) {
            $available = $categories;
        }

        return $available[ array_rand( $available ) ];
    }

    /* =================================================================
     *  PARTNERSHIP CTA
     * ================================================================= */

    /**
     * Return the default Damalion partnership CTA HTML.
     *
     * @return string
     */
    public static function get_partnership_cta() {
        $settings  = get_option( 'dba_startup_hub_settings', array() );

        // Admin override takes priority
        if ( ! empty( $settings['cta_html_override'] ) ) {
            return $settings['cta_html_override'];
        }

        $cta_text      = $settings['cta_text']      ?? 'Damalion supports international investors, entrepreneurs, and family offices navigating the U.S. startup ecosystem with structuring, compliance, and strategic advisory.';
        $cta_link_text = $settings['cta_link_text']  ?? 'Contact your Damalion experts now.';
        $cta_link_url  = $settings['cta_link_url']   ?? 'https://www.damalion.com/lets-connect/';

        return '<div class="dba-startup-hub-cta" style="background:#f0f4f8;border-left:4px solid #1a365d;padding:20px 24px;margin:32px 0;border-radius:4px;">'
            . '<p style="margin:0 0 8px;"><em>' . esc_html( $cta_text ) . '</em></p>'
            . '<p style="margin:0;"><a href="' . esc_url( $cta_link_url ) . '" target="_blank" rel="noopener">'
            . esc_html( $cta_link_text ) . '</a></p>'
            . '</div>';
    }
}
