<?php
/**
 * Plugin Name: Kraftarc Kerala Live Gold & Jewelry Price Sync for WooCommerce
 * Plugin URI: https://keralagold.kraftarc.com
 * Description: Real-time synchronization of Kerala gold, silver & platinum rates for WooCommerce jewelry storefronts. Automated daily repricing, cart calculation engine (Weight × Live Rate + VA + HUID + GST), and morning bullion bulletin sync.
 * Version: 1.0.0
 * Author: Kraftarc Technologies
 * Author URI: https://kraftarc.com
 * License: GPL-2.0+
 * Text Domain: kraftarc-kerala-gold
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * WC requires at least: 5.0
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Kraftarc_Kerala_Gold_Sync {

    const OPTION_KEY = 'kraftarc_kerala_gold_settings';
    const API_ENDPOINT = 'https://keralagold.kraftarc.com/api';

    public function __construct() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_styles']);
        
        // WooCommerce Dynamic Price Calculation Hook
        add_action('woocommerce_before_calculate_totals', [$this, 'recalculate_jewelry_cart_prices'], 20, 1);
        
        // Cron Schedule for Daily 10:15 AM Bullion Sync
        add_filter('cron_schedules', [$this, 'add_custom_cron_intervals']);
        add_action('kraftarc_daily_gold_sync_event', [$this, 'perform_daily_sync']);
        
        // Shortcodes
        add_shortcode('kerala_gold_rate_ticker', [$this, 'render_rates_ticker_shortcode']);

        register_activation_hook(__FILE__, [$this, 'activate_plugin']);
        register_deactivation_hook(__FILE__, [$this, 'deactivate_plugin']);
    }

    public function activate_plugin() {
        if (!wp_next_scheduled('kraftarc_daily_gold_sync_event')) {
            // Schedule at 10:15 AM IST (04:45 UTC)
            wp_schedule_event(time(), 'daily', 'kraftarc_daily_gold_sync_event');
        }
    }

    public function deactivate_plugin() {
        wp_clear_scheduled_hook('kraftarc_daily_gold_sync_event');
    }

    public function add_custom_cron_intervals($schedules) {
        $schedules['every_six_hours'] = [
            'interval' => 21600,
            'display'  => __('Every 6 Hours', 'kraftarc-kerala-gold')
        ];
        return $schedules;
    }

    public function add_admin_menu() {
        add_submenu_page(
            'woocommerce',
            __('Kerala Gold Rates Sync', 'kraftarc-kerala-gold'),
            __('Kerala Gold Sync', 'kraftarc-kerala-gold'),
            'manage_woocommerce',
            'kraftarc-kerala-gold',
            [$this, 'render_admin_page']
        );
    }

    public function register_settings() {
        register_setting('kraftarc_gold_settings_group', self::OPTION_KEY);
    }

    public function get_settings() {
        $defaults = [
            'api_key' => '',
            'api_url' => self::API_ENDPOINT,
            'default_purity' => '22k',
            'default_va_type' => 'percentage',
            'default_va_value' => '12.0',
            'include_huid' => 'yes',
            'huid_charge' => '45',
            'apply_gst' => 'yes',
            'gst_percentage' => '3.0',
            'auto_sync' => 'yes',
            'last_sync_timestamp' => '',
            'cached_rate_22k' => 0,
            'cached_rate_24k' => 0,
            'cached_rate_18k' => 0
        ];
        return wp_parse_args(get_option(self::OPTION_KEY, []), $defaults);
    }

    public function perform_daily_sync() {
        $settings = $this->get_settings();
        $apiKey = trim($settings['api_key']);
        if (empty($apiKey)) return;

        $response = wp_remote_get(rtrim($settings['api_url'], '/') . '/rates/gold', [
            'headers' => [
                'x-api-key' => $apiKey,
                'User-Agent' => 'WooCommerce-KeralaGoldSync/1.0'
            ],
            'timeout' => 15
        ]);

        if (is_wp_error($response)) {
            error_log('Kraftarc Gold Sync Error: ' . $response->get_error_message());
            return;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code === 200) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($data['gold'])) {
                $settings['cached_rate_22k'] = $data['gold']['22k']['per_gram'] ?? 0;
                $settings['cached_rate_24k'] = $data['gold']['24k']['per_gram'] ?? 0;
                $settings['cached_rate_18k'] = $data['gold']['18k']['per_gram'] ?? 0;
                $settings['last_sync_timestamp'] = current_time('mysql');
                update_option(self::OPTION_KEY, $settings);
            }
        }
    }

    /**
     * Recalculates cart product prices based on live Kerala gold rates and product weight
     */
    public function recalculate_jewelry_cart_prices($cart) {
        if (is_admin() && !defined('DOING_AJAX')) return;
        if (did_action('woocommerce_before_calculate_totals') >= 2) return;

        $settings = $this->get_settings();
        $rate22k = floatval($settings['cached_rate_22k']);
        if ($rate22k <= 0) return;

        foreach ($cart->get_cart() as $cart_item) {
            $product = $cart_item['data'];
            if (!$product) continue;

            $is_jewelry = get_post_meta($product->get_id(), '_is_kerala_jewelry', true);
            $weight_grams = floatval(get_post_meta($product->get_id(), '_jewelry_weight_grams', true));
            if (!$weight_grams && method_exists($product, 'get_weight')) {
                $weight_grams = floatval($product->get_weight());
            }

            if ($is_jewelry === 'yes' && $weight_grams > 0) {
                $purity = get_post_meta($product->get_id(), '_jewelry_purity', true) ?: $settings['default_purity'];
                $rate = $purity === '24k' ? floatval($settings['cached_rate_24k']) : ($purity === '18k' ? floatval($settings['cached_rate_18k']) : $rate22k);

                $va_val = floatval(get_post_meta($product->get_id(), '_making_charge_value', true) ?: $settings['default_va_value']);
                $huid = ($settings['include_huid'] === 'yes') ? floatval($settings['huid_charge']) : 0;
                $gst_pct = ($settings['apply_gst'] === 'yes') ? floatval($settings['gst_percentage']) : 0;

                // Base calculation
                $metal_base = $weight_grams * $rate;
                $va_amount = ($metal_base * ($va_val / 100.0));
                $subtotal = $metal_base + $va_amount + $huid;
                $gst_amount = $subtotal * ($gst_pct / 100.0);
                $final_price = round($subtotal + $gst_amount, 2);

                $product->set_price($final_price);
            }
        }
    }

    public function render_rates_ticker_shortcode() {
        $settings = $this->get_settings();
        $rate22k = number_format(floatval($settings['cached_rate_22k']), 2);
        $rate24k = number_format(floatval($settings['cached_rate_24k']), 2);
        $pavan = number_format(floatval($settings['cached_rate_22k']) * 8, 2);

        return '<div class="kraftarc-gold-ticker" style="background:#26251e; color:#f7f7f4; padding:8px 16px; border-radius:4px; font-family:monospace; display:inline-flex; gap:16px; align-items:center;">
            <span style="color:#c59b27; font-weight:bold;">⚡ KERALA GOLD:</span>
            <span>22K (1g): ₹' . esc_html($rate22k) . '</span>
            <span>22K (8g Pavan): ₹' . esc_html($pavan) . '</span>
            <span>24K (1g): ₹' . esc_html($rate24k) . '</span>
        </div>';
    }

    public function enqueue_frontend_styles() {
        // Front-end widget styles
    }

    public function render_admin_page() {
        $settings = $this->get_settings();
        
        $notice = '';
        if (isset($_POST['kraftarc_test_sync']) && check_admin_referer('kraftarc_test_sync_action')) {
            $this->perform_daily_sync();
            $settings = $this->get_settings();
            $notice = '<div class="notice notice-success is-dismissible"><p><strong>Success:</strong> Synchronized live Kerala rates from Kraftarc Edge Gateway!</p></div>';
        }
        ?>
        <div class="wrap">
            <h1>💎 KeralaGoldAPI — WooCommerce Integration</h1>
            <p>Connect your WooCommerce store to <strong>KeralaGoldAPI</strong> for live rates and automated jewelry checkout repricing.</p>
            <?php echo $notice; ?>

            <div style="display: flex; gap: 24px; margin-top: 20px;">
                <div style="flex: 2; background: #fff; padding: 24px; border: 1px solid #ccd0d4; border-radius: 4px;">
                    <form method="post" action="options.php">
                        <?php settings_fields('kraftarc_gold_settings_group'); ?>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><label for="api_key">Live API Key</label></th>
                                <td>
                                    <input type="password" id="api_key" name="<?php echo self::OPTION_KEY; ?>[api_key]" value="<?php echo esc_attr($settings['api_key']); ?>" class="regular-text" placeholder="kg_live_..." />
                                    <p class="description">Get your API key from your <a href="https://keralagold.kraftarc.com/dashboard" target="_blank">Kraftarc Dashboard</a>.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="api_url">API Gateway URL</label></th>
                                <td>
                                    <input type="text" id="api_url" name="<?php echo self::OPTION_KEY; ?>[api_url]" value="<?php echo esc_attr($settings['api_url']); ?>" class="regular-text" />
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Default Making Charge (VA %)</th>
                                <td>
                                    <input type="number" step="0.1" name="<?php echo self::OPTION_KEY; ?>[default_va_value]" value="<?php echo esc_attr($settings['default_va_value']); ?>" class="small-text" /> %
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">BIS Hallmarking Fee (HUID)</th>
                                <td>
                                    <label><input type="checkbox" name="<?php echo self::OPTION_KEY; ?>[include_huid]" value="yes" <?php checked($settings['include_huid'], 'yes'); ?> /> Add ₹45 standard HUID per jewelry item</label>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Goods and Services Tax (GST)</th>
                                <td>
                                    <label><input type="checkbox" name="<?php echo self::OPTION_KEY; ?>[apply_gst]" value="yes" <?php checked($settings['apply_gst'], 'yes'); ?> /> Apply standard 3% GST</label>
                                </td>
                            </tr>
                        </table>
                        <?php submit_button('Save Settings'); ?>
                    </form>
                </div>

                <div style="flex: 1; background: #fdfdfd; padding: 20px; border: 1px solid #e2e4e7; border-radius: 4px;">
                    <h3 style="margin-top:0;">📡 Connection Status</h3>
                    <p><strong>22K Gold (1g):</strong> ₹<?php echo esc_html(number_format(floatval($settings['cached_rate_22k']), 2)); ?></p>
                    <p><strong>22K Pavan (8g):</strong> ₹<?php echo esc_html(number_format(floatval($settings['cached_rate_22k']) * 8, 2)); ?></p>
                    <p><strong>24K Gold (1g):</strong> ₹<?php echo esc_html(number_format(floatval($settings['cached_rate_24k']), 2)); ?></p>
                    <p><strong>Last Sync:</strong> <?php echo esc_html($settings['last_sync_timestamp'] ?: 'Never'); ?></p>

                    <form method="post" action="">
                        <?php wp_nonce_field('kraftarc_test_sync_action'); ?>
                        <input type="submit" name="kraftarc_test_sync" class="button button-primary" value="🔄 Test API &amp; Sync Now" />
                    </form>

                    <hr style="margin: 20px 0; border: 0; border-top: 1px solid #eee;" />
                    <h4>Need More Requests?</h4>
                    <p>Free Tier provides 1,000 monthly requests. To enable auto-repricing for 100+ products, upgrade to <strong>Pro Store (250,000 req/mo)</strong>.</p>
                    <a href="https://keralagold.kraftarc.com/dashboard#upgrade" target="_blank" class="button button-secondary">Upgrade Plan</a>
                </div>
            </div>
        </div>
        <?php
    }
}

new Kraftarc_Kerala_Gold_Sync();
