<?php
/**
 * Plugin Name: Samanta Menu Display
 * Plugin URI: https://cukierniasamanta.pl
 * Description: Display restaurant menu from JSON data or standalone HTML files with full cart & share functionality
 * Version: 2.0.0
 * Author: Samanta CRM
 * Text Domain: samanta-menu
 */

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

define('SAMANTA_MENU_VERSION', '2.0.0');
define('SAMANTA_MENU_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SAMANTA_MENU_PLUGIN_URL', plugin_dir_url(__FILE__));

class Samanta_Menu_Plugin {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'admin_scripts'));
        add_action('wp_ajax_samanta_upload_menu', array($this, 'ajax_upload_menu'));
        add_action('wp_ajax_samanta_delete_menu', array($this, 'ajax_delete_menu'));
        add_action('wp_ajax_samanta_upload_standalone_html', array($this, 'ajax_upload_standalone_html'));
        add_action('wp_ajax_samanta_delete_standalone_html', array($this, 'ajax_delete_standalone_html'));
        
        // Register shortcode
        add_shortcode('samanta_menu', array($this, 'menu_shortcode'));
        add_shortcode('samanta_locations', array($this, 'locations_shortcode'));
        add_shortcode('samanta_standalone', array($this, 'standalone_shortcode'));
        
        // Enqueue frontend scripts
        add_action('wp_enqueue_scripts', array($this, 'frontend_scripts'));
    }
    
    public function add_admin_menu() {
        add_menu_page(
            'Samanta Menu',
            'Menu Lokali',
            'manage_options',
            'samanta-menu',
            array($this, 'admin_page'),
            'dashicons-food',
            30
        );
    }
    
    public function register_settings() {
        register_setting('samanta_menu_settings', 'samanta_menu_data');
    }
    
    public function admin_scripts($hook) {
        if ('toplevel_page_samanta-menu' !== $hook) {
            return;
        }
        
        wp_enqueue_style('samanta-menu-admin', SAMANTA_MENU_PLUGIN_URL . 'assets/admin.css', array(), SAMANTA_MENU_VERSION);
        wp_enqueue_script('samanta-menu-admin', SAMANTA_MENU_PLUGIN_URL . 'assets/admin.js', array('jquery'), SAMANTA_MENU_VERSION, true);
        
        wp_localize_script('samanta-menu-admin', 'samantaMenu', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('samanta_menu_nonce')
        ));
    }
    
    public function frontend_scripts() {
        if (!is_singular() && !is_page()) {
            return;
        }
        
        global $post;
        if (has_shortcode($post->post_content, 'samanta_menu') || has_shortcode($post->post_content, 'samanta_locations')) {
            wp_enqueue_style('bootstrap', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css', array(), '5.3.3');
            wp_enqueue_style('aos', 'https://unpkg.com/aos@2.3.4/dist/aos.css', array(), '2.3.4');
            wp_enqueue_style('samanta-menu', SAMANTA_MENU_PLUGIN_URL . 'assets/menu.css', array(), SAMANTA_MENU_VERSION);
            
            wp_enqueue_script('bootstrap', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js', array(), '5.3.3', true);
            wp_enqueue_script('aos', 'https://unpkg.com/aos@2.3.4/dist/aos.js', array(), '2.3.4', true);
            wp_enqueue_script('samanta-menu', SAMANTA_MENU_PLUGIN_URL . 'assets/menu.js', array('jquery'), SAMANTA_MENU_VERSION, true);
        }
    }
    
    public function admin_page() {
        include SAMANTA_MENU_PLUGIN_DIR . 'admin/admin-page.php';
    }
    
    public function ajax_upload_standalone_html() {
        check_ajax_referer('samanta_menu_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }
        
        if (!isset($_FILES['html_file'])) {
            wp_send_json_error('No file uploaded');
        }
        
        $file = $_FILES['html_file'];
        
        if ($file['type'] !== 'text/html') {
            wp_send_json_error('Invalid file type. Please upload an HTML file.');
        }
        
        $html_content = file_get_contents($file['tmp_name']);
        
        // Extract location name from HTML title or content
        preg_match('/<title>(.*?)<\/title>/', $html_content, $title_matches);
        $location_name = isset($title_matches[1]) ? trim(str_replace('– Menu', '', $title_matches[1])) : 'Menu';
        
        // Get existing menus
        $menus = get_option('samanta_menu_standalone_html', array());
        
        // Generate unique ID
        $menu_id = uniqid('menu_');
        
        // Store HTML content
        $menus[$menu_id] = array(
            'location_name' => $location_name,
            'html_content' => $html_content,
            'uploaded_at' => current_time('mysql'),
            'file_name' => $file['name']
        );
        
        update_option('samanta_menu_standalone_html', $menus);
        
        wp_send_json_success(array(
            'message' => 'HTML file uploaded successfully',
            'menu_id' => $menu_id,
            'location_name' => $location_name
        ));
    }
    
    public function ajax_delete_standalone_html() {
        check_ajax_referer('samanta_menu_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }
        
        $menu_id = isset($_POST['menu_id']) ? sanitize_text_field($_POST['menu_id']) : '';
        
        if (empty($menu_id)) {
            wp_send_json_error('Invalid menu ID');
        }
        
        $menus = get_option('samanta_menu_standalone_html', array());
        
        if (!isset($menus[$menu_id])) {
            wp_send_json_error('Menu not found');
        }
        
        unset($menus[$menu_id]);
        update_option('samanta_menu_standalone_html', $menus);
        
        wp_send_json_success('Menu deleted successfully');
    }
    
    public function ajax_upload_menu() {
        check_ajax_referer('samanta_menu_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }
        
        if (!isset($_FILES['menu_file'])) {
            wp_send_json_error('No file uploaded');
        }
        
        $file = $_FILES['menu_file'];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error('Upload error');
        }
        
        $json_content = file_get_contents($file['tmp_name']);
        $menu_data = json_decode($json_content, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error('Invalid JSON file');
        }
        
        // Validate structure
        if (!isset($menu_data['location']) || !isset($menu_data['categories'])) {
            wp_send_json_error('Invalid menu structure');
        }
        
        // Get existing menus
        $menus = get_option('samanta_menu_data', array());
        if (!is_array($menus)) {
            $menus = array();
        }
        
        // Add new menu
        $location_id = $menu_data['location']['id'];
        $menus[$location_id] = $menu_data;
        
        update_option('samanta_menu_data', $menus);
        
        wp_send_json_success(array(
            'message' => 'Menu uploaded successfully',
            'location' => $menu_data['location']['name']
        ));
    }
    
    public function ajax_delete_menu() {
        check_ajax_referer('samanta_menu_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
        }
        
        $location_id = isset($_POST['location_id']) ? intval($_POST['location_id']) : 0;
        
        if (!$location_id) {
            wp_send_json_error('Invalid location ID');
        }
        
        $menus = get_option('samanta_menu_data', array());
        
        if (isset($menus[$location_id])) {
            unset($menus[$location_id]);
            update_option('samanta_menu_data', $menus);
            wp_send_json_success('Menu deleted');
        } else {
            wp_send_json_error('Menu not found');
        }
    }
    
    public function locations_shortcode($atts) {
        $menus = get_option('samanta_menu_data', array());
        
        if (empty($menus)) {
            return '<p>No menus available</p>';
        }
        
        ob_start();
        include SAMANTA_MENU_PLUGIN_DIR . 'templates/locations.php';
        return ob_get_clean();
    }
    
    public function menu_shortcode($atts) {
        $atts = shortcode_atts(array(
            'location' => ''
        ), $atts);
        
        $location_id = intval($atts['location']);
        
        if (!$location_id && isset($_GET['location'])) {
            $location_id = intval($_GET['location']);
        }
        
        if (!$location_id) {
            return '<p>Please specify a location</p>';
        }
        
        $menus = get_option('samanta_menu_data', array());
        
        if (!isset($menus[$location_id])) {
            return '<p>Menu not found for this location</p>';
        }
        
        $menu_data = $menus[$location_id];
        
        ob_start();
        include SAMANTA_MENU_PLUGIN_DIR . 'templates/menu-display.php';
        return ob_get_clean();
    }
    
    public function standalone_shortcode($atts) {
        $atts = shortcode_atts(array(
            'id' => ''
        ), $atts);
        
        $menu_id = sanitize_text_field($atts['id']);
        
        if (!$menu_id && isset($_GET['menu_id'])) {
            $menu_id = sanitize_text_field($_GET['menu_id']);
        }
        
        $menus = get_option('samanta_menu_standalone_html', array());
        
        // If no ID specified, show list
        if (!$menu_id) {
            if (empty($menus)) {
                return '<p>No standalone menus available</p>';
            }
            
            $output = '<div class="samanta-standalone-list">';
            $output .= '<h3>Available Menus:</h3>';
            $output .= '<ul>';
            foreach ($menus as $id => $menu) {
                $url = add_query_arg('menu_id', $id, get_permalink());
                $output .= '<li><a href="' . esc_url($url) . '">' . esc_html($menu['location_name']) . '</a></li>';
            }
            $output .= '</ul>';
            $output .= '</div>';
            return $output;
        }
        
        if (!isset($menus[$menu_id])) {
            return '<p>Menu not found</p>';
        }
        
        $html_content = $menus[$menu_id]['html_content'];
        
        // Extract body content (strip html/head tags) to embed in WordPress page
        preg_match('/<body[^>]*>(.*?)<\/body>/is', $html_content, $body_matches);
        
        if (isset($body_matches[1])) {
            // Extract styles
            preg_match('/<style[^>]*>(.*?)<\/style>/is', $html_content, $style_matches);
            $styles = isset($style_matches[1]) ? $style_matches[1] : '';
            
            // Extract scripts
            preg_match_all('/<script[^>]*>(.*?)<\/script>/is', $html_content, $script_matches);
            $scripts = isset($script_matches[1]) ? implode("\n", $script_matches[1]) : '';
            
            $output = '<div class="samanta-standalone-menu">';
            if ($styles) {
                $output .= '<style>' . $styles . '</style>';
            }
            $output .= $body_matches[1];
            if ($scripts) {
                $output .= '<script>' . $scripts . '</script>';
            }
            $output .= '</div>';
            
            return $output;
        }
        
        // If extraction fails, return full HTML in iframe
        return '<iframe srcdoc="' . esc_attr($html_content) . '" style="width: 100%; min-height: 100vh; border: none;"></iframe>';
    }
}

// Initialize plugin
Samanta_Menu_Plugin::get_instance();
