<?php
/**
 * Local SEO — Local Business schema, Google Business Profile fields
 */
if (!defined('ABSPATH')) exit;

class SEOFORGE_Local_Seo {
    private static $instance = null;
    public static function instance() { if (!self::$instance) self::$instance = new self(); return self::$instance; }

    private function __construct() {
        if (!SEOFORGE_License::instance()->can('local_seo')) {
            return;
        }

        add_action('wp_head', [$this, 'output_local_schema'], 6);
    }

    /**
 * Get local business settings
 */
    public static function get_settings() {
        $defaults = [
            'enabled'      => false,
            'business_name'=> '',
            'business_type'=> 'LocalBusiness',
            'phone'        => '',
            'email'        => '',
            'street'       => '',
            'city'         => '',
            'state'        => '',
            'zip'          => '',
            'country'      => '',
            'lat'          => '',
            'lng'          => '',
            'opening_hours'=> '',
            'price_range'  => '',
            'logo_url'     => '',
            'image_url'    => '',
            'social_urls'  => '',
        ];
        // get_option's $default is ignored once the row exists; merge over defaults so a partial save can't leave keys undefined.
        return wp_parse_args(get_option('seoforge_local_seo', []), $defaults);
    }

    /**
 * Output LocalBusiness JSON-LD schema
 */
    public function output_local_schema() {
        if (!is_front_page() && !is_page()) return;

        $s = self::get_settings();
        if (empty($s['enabled']) || empty($s['business_name'])) return;

        $schema = [
            '@context' => 'https://schema.org',
            '@type'    => $s['business_type'] ?: 'LocalBusiness',
            'name'     => $s['business_name'],
            'url'      => home_url('/'),
        ];

        if ($s['phone'])  $schema['telephone'] = $s['phone'];
        if ($s['email'])  $schema['email'] = $s['email'];

        // Address
        if ($s['street'] || $s['city']) {
            $schema['address'] = [
                '@type'           => 'PostalAddress',
                'streetAddress'   => $s['street'],
                'addressLocality' => $s['city'],
                'addressRegion'   => $s['state'],
                'postalCode'      => $s['zip'],
                'addressCountry'  => $s['country'],
            ];
        }

        // Geo coordinates
        if ($s['lat'] && $s['lng']) {
            $schema['geo'] = [
                '@type'     => 'GeoCoordinates',
                'latitude'  => $s['lat'],
                'longitude' => $s['lng'],
            ];
        }

        if ($s['logo_url'])    $schema['logo'] = $s['logo_url'];
        if ($s['image_url'])   $schema['image'] = $s['image_url'];
        if ($s['price_range']) $schema['priceRange'] = $s['price_range'];

        // Opening hours
        if ($s['opening_hours']) {
            $schema['openingHours'] = array_map('trim', explode("\n", $s['opening_hours']));
        }

        // Social profiles
        if ($s['social_urls']) {
            $schema['sameAs'] = array_filter(array_map('trim', explode("\n", $s['social_urls'])));
        }

        echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . '</script>' . "\n";
    }

    /**
 * Business types for dropdown
 */
    public static function get_business_types() {
        return [
            'Organization'        => 'Organization (Online / No Physical Location)',
            'ProfessionalService' => 'Professional Service (Freelancer / Agency)',
            'LocalBusiness'       => 'Local Business (Generic)',
            'Restaurant'          => 'Restaurant',
            'BarOrPub'            => 'Bar / Pub',
            'CafeOrCoffeeShop'    => 'Cafe / Coffee Shop',
            'Bakery'              => 'Bakery',
            'Store'               => 'Store (Generic)',
            'ClothingStore'       => 'Clothing Store',
            'ElectronicsStore'    => 'Electronics Store',
            'GroceryStore'        => 'Grocery Store',
            'HardwareStore'       => 'Hardware Store',
            'AutoDealer'          => 'Auto Dealer',
            'AutoRepair'          => 'Auto Repair',
            'BeautySalon'         => 'Beauty Salon',
            'HairSalon'           => 'Hair Salon',
            'HealthClub'          => 'Health Club / Gym',
            'Dentist'             => 'Dentist',
            'MedicalClinic'       => 'Medical Clinic',
            'Pharmacy'            => 'Pharmacy',
            'Veterinarian'        => 'Veterinarian',
            'LegalService'        => 'Legal Service',
            'AccountingService'   => 'Accounting Service',
            'RealEstateAgent'     => 'Real Estate Agent',
            'InsuranceAgency'     => 'Insurance Agency',
            'TravelAgency'        => 'Travel Agency',
            'Hotel'               => 'Hotel',
            'Plumber'             => 'Plumber',
            'Electrician'         => 'Electrician',
            'LocksmithService'    => 'Locksmith',
        ];
    }
}
