<?php

namespace EasyRestaurantManager\Models;

class Menu extends Model
{
    protected $model = 'erm_menu_items';

    public static function store($menu)
    {
        global $wpdb;
        
        if (isset($menu['portion_sizes']) && is_array($menu['portion_sizes'])) {
            $menu['portion_sizes'] = json_encode($menu['portion_sizes']);
        }

        if (isset($menu['addons']) && is_array($menu['addons'])) {
            $menu['addons'] = json_encode($menu['addons']);
        }
    
        $post_data = [
            'post_title'    => sanitize_text_field($menu['name']),
            'post_status'   => 'publish',
            'post_author'   => get_current_user_id(),
            'post_type'     => 'erm_menu',
            'post_name'     => sanitize_text_field($menu['name'])
        ];

        $post_id = wp_insert_post($post_data, true);

        if (is_wp_error($post_id)) {
            return false;
        }

        $menu['post_id'] = $post_id;

        $inserted = $wpdb->insert(
            $wpdb->prefix . 'erm_menu_items', $menu,
        );

        // Check for insert failure
        if (!$inserted) {
            return false;
        }

        $post_content = "[easy_restaurant_manager_menus_single menu_id=$wpdb->insert_id]";
        wp_update_post([
            'ID'           => $post_id,
            'post_content' => $post_content
        ]);

        return $post_data;
    }

    public static function updateMenu($data)
    {
        global $wpdb;


        $id = (int) $data['id'];
        unset($data['id']);
        if (isset($data['portion_sizes']) && is_array($data['portion_sizes'])) {
            $data['portion_sizes'] = json_encode($data['portion_sizes']);
        }

        if (isset($data['addons']) && is_array($data['addons'])) {
            $data['addons'] = json_encode($data['addons']);
        }
        unset($data['menu_url']);
        $updated = $wpdb->update( $wpdb->prefix . 'erm_menu_items', $data,['id' => $id],null,  ['%d'] );

        if ($updated === false) {
            return false;
        }

        return $updated;
    }

    public static function getMenu()
	{
		global $wpdb;
        $menus = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}erm_menu_items  ORDER BY id DESC");

        foreach ($menus as $menu) {
            $menu->menu_url = get_permalink($menu->post_id);
        }

        return $menus;
	}

    public static function getMenuById($id)
    {
        global $wpdb;
        $menu = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}erm_menu_items WHERE id = %d", $id));
        $menu->menu_url = get_permalink($menu->post_id);
        $menu->category = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}erm_menu_categories WHERE id = %d", $menu->category_id));
        return $menu;
    }



    public static function getMenuByCategory()
    {
        global $wpdb;

        $items = $wpdb->get_results(
            $wpdb->prepare("
                SELECT mi.*, c.name AS category_name
                FROM {$wpdb->prefix}erm_menu_items mi
                LEFT JOIN {$wpdb->prefix}erm_menu_categories c ON mi.category_id = c.id
                ORDER BY c.name ASC, mi.id DESC
            ")
        );

        // Initialize the menuSections array
        $menuSections = [];

        // Group the items by category
        foreach ($items as $item) {
            // Check if the category already exists in the array
            if (!isset($menuSections[$item->category_name])) {
                // If not, create a new section for this category
                $menuSections[$item->category_name] = [
                    'name' => $item->category_name,
                    'items' => []
                ];
            }
    
            // Add the item to the appropriate category
            $menuSections[$item->category_name]['items'][] = [
                'name' => $item->name,
                'description' => $item->description,
                'price' => $item->base_price,
                'image' => $item->image,
                'id' => $item->name,
                'category_id' => $item->category_id,
                'branch_id' => $item->branch_id,
                'portion_sizes' => $item->portion_sizes,
                'addons' => $item->addons,
                'availability' => $item->availability
            ];
        }
  
        // Convert the associative array to a sequential array of sections
        $menuSections = array_values($menuSections);
        // dd($menuSections);
        return $menuSections;
    }

    public static function deleteMenu($id){
        global $wpdb;
        $post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->prefix}erm_menu_items WHERE id = %d", $id));
        if ($post_id) {
            wp_delete_post($post_id, true);
        }
        
        $res = $wpdb->delete($wpdb->prefix . 'erm_menu_items', ['id' => $id]);
        return $res;
    }
}
