<?php
/**
 * Extendable functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Extendable
 * @since Extendable 1.0
 */

/* ---------------------------------------------------------------------------
   1. FUNZIONI BASE DEL TEMA (NON MODIFICARE SE GIÀ PRESENTI)
--------------------------------------------------------------------------- */
if ( ! function_exists( 'extendable_support' ) ) :
	function extendable_support() {
		add_theme_support( 'wp-block-styles' );
		global $wp_version;
		if ( version_compare( $wp_version, '6.0.2', '<=' ) ) {
			$editor_style = array(
				'style.css',
				'/assets/css/deprecate-style.css',
			);
		} else {
			$editor_style = 'style.css';
		}
		add_editor_style( $editor_style );
	}
endif;
add_action( 'after_setup_theme', 'extendable_support' );

if ( ! function_exists( 'extendable_styles' ) ) :
	function extendable_styles() {
		$theme_version = wp_get_theme()->get( 'Version' );
		$version_string = is_string( $theme_version ) ? $theme_version : false;
		wp_register_style(
			'extendable-style',
			get_template_directory_uri() . '/style.css',
			array(),
			$version_string
		);
		wp_enqueue_style( 'extendable-style' );
		global $wp_version;
		if ( version_compare( $wp_version, '6.0.2', '<=' ) ) {
			wp_register_style(
				'extendable-deprecate-style',
				get_template_directory_uri() . '/assets/css/deprecate-style.css',
				array(),
				$version_string
			);
			wp_enqueue_style( 'extendable-deprecate-style' );
		}
	}
endif;
add_action( 'wp_enqueue_scripts', 'extendable_styles' );

function extendable_enqueue_block_styles() {
	if ( has_block( 'contact-form-7/contact-form-selector' ) ) {
		wp_enqueue_style(
			'extendable-contact-form-7-style',
			get_template_directory_uri() . '/assets/css/contact-form-7.css',
			array(),
			'1.0.0'
		);
	}
	if ( has_block( 'wpforms/form-selector' ) ) {
		wp_enqueue_style(
			'extendable-wpforms-style',
			get_template_directory_uri() . '/assets/css/wpforms.css',
			array(),
			'1.0.0'
		);
	}
}
add_action( 'enqueue_block_assets', 'extendable_enqueue_block_styles' );

function extendable_register_pattern_categories() {
	$block_pattern_categories = array(
		'header' => array( 'label' => __( 'Headers', 'extendable' ) ),
		'footer' => array( 'label' => __( 'Footers', 'extendable' ) ),
	);
	$block_pattern_categories = apply_filters( 'extendable_block_pattern_categories', $block_pattern_categories );
	foreach ( $block_pattern_categories as $name => $properties ) {
		if ( ! WP_Block_Pattern_Categories_Registry::get_instance()->is_registered( $name ) ) {
			register_block_pattern_category( $name, $properties );
		}
	}
}
add_action( 'init', 'extendable_register_pattern_categories', 9 );

/* ---------------------------------------------------------------------------
   2. GESTIONE CATEGORIE E PRODOTTI ([register_data])
--------------------------------------------------------------------------- */
function myplugin_get_external_db() {
	return new wpdb("gestj8_adminbar", "Hitler2025?", "gestj8_gestionebar", "tb-be04-linweb152.srv.teamblue-ops.net:3306");
}

function myplugin_ajax_delete_category() {
	$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
	if ($id > 0) {
		$db = myplugin_get_external_db();
		$result = $db->query($db->prepare("DELETE FROM categorie WHERE id = %d", $id));
		if ($result !== false) {
			wp_send_json_success(array("id" => $id));
		}
	}
	wp_send_json_error();
}
add_action('wp_ajax_myplugin_delete_category', 'myplugin_ajax_delete_category');
add_action('wp_ajax_nopriv_myplugin_delete_category', 'myplugin_ajax_delete_category');

function myplugin_ajax_delete_product() {
	$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
	if ($id > 0) {
		$db = myplugin_get_external_db();
		$result = $db->query($db->prepare("DELETE FROM prodotti WHERE id = %d", $id));
		if ($result !== false) {
			wp_send_json_success(array("id" => $id));
		}
	}
	wp_send_json_error();
}
add_action('wp_ajax_myplugin_delete_product', 'myplugin_ajax_delete_product');
add_action('wp_ajax_nopriv_myplugin_delete_product', 'myplugin_ajax_delete_product');

function get_register_data() {
	$output = '<p>Gestione categorie e prodotti (codice stabile) qui...</p>';
	return $output;
}
add_shortcode("register_data", "get_register_data");

/* ---------------------------------------------------------------------------
   3. GESTIONE TAVOLI E SCONTRINO ([table_management])
---------------------------------------------------------------------------*/

/**
 * Shortcode: [table_management]
 *
 * Gestisce la creazione/modifica/eliminazione di aree, tavoli e ordini.
 * Se viene passato "table_id" nella URL, mostra il dettaglio dello scontrino.
 * Lo scontrino è formattato per stampanti termiche (~8cm di larghezza) con:
 *  - Logo centrato (con larghezza fissa di 4cm)
 *  - Indirizzo e P.IVA centrati
 *  - "Ordine - [numero] - Tavolo n°X" centrato
 *  - Elenco prodotti con descrizione a sinistra e prezzo a destra
 *  - Totale a destra
 *  - Data/ora centrati
 * Il testo dello scontrino (sia a video che in stampa) usa "Impact", 40px, bold.
 */
function get_table_management() {

	// Avvia la sessione per il numero d'ordine (es: 22 -> 22000)
	if (!session_id()) {
		session_start();
	}
	$current_day = date("d");
	if (!isset($_SESSION['order_day']) || $_SESSION['order_day'] != $current_day) {
		$_SESSION['order_day'] = $current_day;
		$_SESSION['order_number'] = $current_day . "000";
	}

	// Connessione al database
	$db_host     = "tb-be04-linweb152.srv.teamblue-ops.net:3306";
	$db_user     = "gestj8_adminbar";
	$db_password = "Hitler2025?";
	$db_name     = "gestj8_gestionebar";
	$db = new wpdb($db_user, $db_password, $db_name, $db_host);
	if (!empty($db->error)) {
		return '<p style="color:red;">Errore di connessione al database: ' . esc_html($db->error) . '</p>';
	}

	// Variabile per eventuali messaggi di errore (es. tavolo duplicato)
	$error_msg = '';

	// Gestione POST per azioni: aree, tavoli, ordini, ecc.
	if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
		switch ($_POST['action']) {

			case 'create_area':
				$area_name = isset($_POST['area_name']) ? sanitize_text_field($_POST['area_name']) : '';
				if (!empty($area_name)) {
					$db->insert('aree', array('nome' => $area_name), array('%s'));
				}
				break;

			case 'edit_area':
				$area_id = isset($_POST['area_id']) ? intval($_POST['area_id']) : 0;
				$area_name = isset($_POST['area_name']) ? sanitize_text_field($_POST['area_name']) : '';
				if ($area_id > 0 && !empty($area_name)) {
					$db->update('aree', array('nome' => $area_name), array('id' => $area_id), array('%s'), array('%d'));
				}
				break;

			case 'delete_area':
				$area_id = isset($_POST['area_id']) ? intval($_POST['area_id']) : 0;
				if ($area_id > 0) {
					$db->delete('aree', array('id' => $area_id), array('%d'));
					$db->delete('tavolo', array('area_id' => $area_id), array('%d'));
				}
				break;

			case 'create_table':
				$area_id = isset($_POST['area_id']) ? intval($_POST['area_id']) : 0;
				$table_num = isset($_POST['table_num']) ? sanitize_text_field($_POST['table_num']) : '';
				if ($area_id > 0 && !empty($table_num)) {
					$exists = $db->get_var($db->prepare(
						"SELECT COUNT(*) FROM tavolo WHERE area_id = %d AND numero = %s",
						$area_id, $table_num
					));
					if ($exists > 0) {
						$error_msg = 'Esiste già un tavolo con questo nome in questa area!';
					} else {
						$db->insert('tavolo', array('numero' => $table_num, 'area_id' => $area_id), array('%s','%d'));
					}
				}
				break;

			case 'edit_table':
				$table_id = isset($_POST['table_id']) ? intval($_POST['table_id']) : 0;
				$table_num = isset($_POST['table_num']) ? sanitize_text_field($_POST['table_num']) : '';
				if ($table_id > 0 && !empty($table_num)) {
					$db->update('tavolo', array('numero' => $table_num), array('id' => $table_id), array('%s'), array('%d'));
				}
				break;

			case 'delete_table':
				$table_id = isset($_POST['table_id']) ? intval($_POST['table_id']) : 0;
				if ($table_id > 0) {
					$db->delete('tavolo', array('id' => $table_id), array('%d'));
				}
				break;

			case 'create_order':
				$table_id = isset($_POST['table_id']) ? intval($_POST['table_id']) : 0;
				$prodotto_id = isset($_POST['prodotto_id']) ? intval($_POST['prodotto_id']) : 0;
				$quantita = isset($_POST['quantita']) ? intval($_POST['quantita']) : 1;
				if ($table_id > 0 && $prodotto_id > 0 && $quantita > 0) {
					$product = $db->get_row("SELECT prezzo FROM prodotti WHERE id = {$prodotto_id}");
					$prezzo = $product ? floatval($product->prezzo) : 0;
					$db->insert('ordini', array(
						'tavolo_id' => $table_id,
						'prodotto_id' => $prodotto_id,
						'quantita' => $quantita,
						'prezzo' => $prezzo,
						'status' => 'non_inviato'
					), array('%d','%d','%d','%f','%s'));
					$_SESSION['order_number']++;
				}
				break;

			case 'delete_order':
				$order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
				if ($order_id > 0) {
					$db->delete('ordini', array('id' => $order_id), array('%d'));
				}
				break;

			case 'clear_order':
				$table_id = isset($_POST['table_id']) ? intval($_POST['table_id']) : 0;
				if ($table_id > 0) {
					$db->query($db->prepare("DELETE FROM ordini WHERE tavolo_id = %d", $table_id));
				}
				break;

			case 'invia_cucina':
				$table_id = isset($_POST['table_id']) ? intval($_POST['table_id']) : 0;
				if ($table_id > 0) {
					$db->query($db->prepare(
						"UPDATE ordini o 
						 JOIN prodotti p ON o.prodotto_id = p.id 
						 JOIN categorie c ON p.categoria_id = c.id 
						 SET o.status = %s 
						 WHERE o.tavolo_id = %d AND c.nome = %s",
						'inviato', $table_id, 'Cucina'
					));
				}
				break;
		}
	}

	$products = $db->get_results("SELECT id, nome, categoria_id, prezzo FROM prodotti ORDER BY nome ASC");
	$all_products = $db->get_results("SELECT * FROM prodotti ORDER BY nome ASC");
	$areas = $db->get_results("SELECT * FROM aree ORDER BY id ASC");
	$tavoli_data = $db->get_results("SELECT * FROM tavolo ORDER BY id ASC");

	$tavoli_by_area = array();
	if ($tavoli_data) {
		foreach ($tavoli_data as $tv) {
			$tavoli_by_area[$tv->area_id][] = $tv;
		}
	}

	$ordini_data = $db->get_results("SELECT tavolo_id, SUM(prezzo * quantita) AS total_cost FROM ordini GROUP BY tavolo_id");
	$ordini_by_table = array();
	if ($ordini_data) {
		foreach ($ordini_data as $od) {
			$ordini_by_table[$od->tavolo_id] = $od->total_cost;
		}
	}

	// CSS per layout e scontrino: in particolare, nella colonna di destra (tm-menu button) il font viene triplicato
	$css = '<style>' . "\n" .
	'  html, body {' . "\n" .
	'    margin: 0; padding: 0; width: 100%; height: 100%;' . "\n" .
	'    background: #1e1e1e; color: #ddd;' . "\n" .
	'    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;' . "\n" .
	'  }' . "\n" .
	'  .tm-container {' . "\n" .
	'    max-width: 1920px; margin: 0 auto; padding: 0 20px;' . "\n" .
	'    box-sizing: border-box;' . "\n" .
	'  }' . "\n" .
	'  .tm-main-header {' . "\n" .
	'    display: flex; align-items: center; gap: 10px; margin-bottom: 10px;' . "\n" .
	'  }' . "\n" .
	'  .tm-main-header h2 {' . "\n" .
	'    margin: 0; color: #fff;' . "\n" .
	'  }' . "\n" .
	'  .tm-main-header .tm-date-header {' . "\n" .
	'    margin-left: auto; font-size: 16px; color: #aaa;' . "\n" .
	'  }' . "\n" .
	'  .tm-area-section {' . "\n" .
	'    border: 1px solid #444; padding: 10px; margin-bottom: 10px;' . "\n" .
	'    background: #2b2b2b;' . "\n" .
	'  }' . "\n" .
	'  .tm-area-header {' . "\n" .
	'    display: flex; justify-content: space-between; align-items: center;' . "\n" .
	'  }' . "\n" .
	'  .tm-area-name {' . "\n" .
	'    font-size: 20px; font-weight: bold; color: #fff;' . "\n" .
	'  }' . "\n" .
	'  .tm-area-settings-btn {' . "\n" .
	'    background: #3498DB; color: #fff; border: none; padding: 8px 12px;' . "\n" .
	'    cursor: pointer; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.7);' . "\n" .
	'    margin-bottom: 15px;' . "\n" .
	'  }' . "\n" .
	'  .tm-tables-row {' . "\n" .
	'    display: grid; grid-template-columns: repeat(4, 1fr);' . "\n" .
	'    gap: 20px; margin-top: 20px;' . "\n" .
	'  }' . "\n" .
	'  .tm-table {' . "\n" .
	'    border: 1px solid #666; padding: 15px; text-align: center;' . "\n" .
	'    border-radius: 8px; cursor: pointer; position: relative;' . "\n" .
	'    background: #333; box-shadow: 0 2px 4px rgba(0,0,0,0.7);' . "\n" .
	'  }' . "\n" .
	'  .tm-table.free {' . "\n" .
	'    background-color: #2d7a2d;' . "\n" .
	'  }' . "\n" .
	'  .tm-table.occupied {' . "\n" .
	'    background-color: #a33;' . "\n" .
	'  }' . "\n" .
	'  .tm-table-settings-btn {' . "\n" .
	'    position: absolute; top: 5px; right: 5px; background: #3498DB;' . "\n" .
	'    color: #fff; border: none; border-radius: 50%;' . "\n" .
	'    width: 24px; height: 24px; font-size: 14px; cursor: pointer;' . "\n" .
	'    box-shadow: 0 2px 4px rgba(0,0,0,0.7);' . "\n" .
	'  }' . "\n" .
	'  .tm-insert-table-btn, .btn {' . "\n" .
	'    background: #3498DB; color: #fff; border: none;' . "\n" .
	'    padding: 8px 12px; cursor: pointer; border-radius: 8px;' . "\n" .
	'    box-shadow: 0 2px 4px rgba(0,0,0,0.7); margin-bottom: 15px;' . "\n" .
	'  }' . "\n" .
	'  .tm-detail-container {' . "\n" .
	'    display: flex; gap: 20px; margin-top: 20px;' . "\n" .
	'  }' . "\n" .
	'  .tm-receipt, .tm-menu {' . "\n" .
	'    flex: 1; padding: 20px;' . "\n" .
	'    border: 1px solid #444; border-radius: 8px;' . "\n" .
	'    background: #2b2b2b; box-shadow: 0 2px 4px rgba(0,0,0,0.7);' . "\n" .
	'  }' . "\n" .
	'  .tm-receipt {' . "\n" .
	'    font-family: \'Impact\', sans-serif !important;' . "\n" .
	'    font-size: 40px !important;' . "\n" .
	'    font-weight: bold !important;' . "\n" .
	'    color: #000 !important;' . "\n" .
	'  }' . "\n" .
	'  .tm-receipt-header {' . "\n" .
	'    text-align: center;' . "\n" .
	'  }' . "\n" .
	'  .tm-receipt-header img {' . "\n" .
	'    width: 4cm !important; display: block; margin: 0 auto;' . "\n" .
	'  }' . "\n" .
	'  .tm-receipt-address {' . "\n" .
	'    text-align: center; font-size: 18px; margin-bottom: 10px;' . "\n" .
	'  }' . "\n" .
	'  .tm-receipt-subheader {' . "\n" .
	'    font-size: 18px; margin-bottom: 10px; text-align: center;' . "\n" .
	'  }' . "\n" .
	'  .tm-order-item {' . "\n" .
	'    display: flex; justify-content: space-between; align-items: center;' . "\n" .
	'    padding: 5px 0; border-bottom: 1px dashed #666;' . "\n" .
	'  }' . "\n" .
	'  .tm-order-item button {' . "\n" .
	'    background: #3498DB; border: none; color: #fff;' . "\n" .
	'    padding: 2px 6px; border-radius: 4px; cursor: pointer;' . "\n" .
	'    margin-right: 5px; box-shadow: 0 1px 3px rgba(0,0,0,0.7);' . "\n" .
	'  }' . "\n" .
	'  .tm-total {' . "\n" .
	'    text-align: right; font-size: 18px; margin-top: 10px;' . "\n" .
	'  }' . "\n" .
	'  .tm-date {' . "\n" .
	'    text-align: center; margin-top: 10px; font-size: 16px; color: #aaa;' . "\n" .
	'  }' . "\n" .
	'  .tm-menu button {' . "\n" .
	'    display: block; width: 100%; margin-bottom: 15px;' . "\n" .
	'    background: #3498DB; color: #fff; border: none;' . "\n" .
	'    padding: 12px; border-radius: 8px; cursor: pointer;' . "\n" .
	'    box-shadow: 0 2px 4px rgba(0,0,0,0.7);' . "\n" .
	'    font-size: 3em !important;' . "\n" .  // Triplica la dimensione del testo
	'  }' . "\n" .
	'  @media print {' . "\n" .
	'    .tm-order-item button { display: none; }' . "\n" .
	'    .tm-menu button { display: none; }' . "\n" .
	'  }' . "\n" .
	'  .product-box {' . "\n" .
	'    border: 1px solid #555; background: #222; color: #ddd;' . "\n" .
	'    padding: 10px; margin-bottom: 10px; border-radius: 4px;' . "\n" .
	'    text-align: left; cursor: pointer;' . "\n" .
	'  }' . "\n" .
	'  .product-box .product-name {' . "\n" .
	'    font-weight: bold; margin-bottom: 5px;' . "\n" .
	'  }' . "\n" .
	'  .product-box .product-price {' . "\n" .
	'    font-size: 14px; color: #aaa;' . "\n" .
	'  }' . "\n" .
	'</style>';
	
	$output .= $css;
	$output .= '<div class="tm-container">';

	if (!empty($error_msg)) {
		$output .= '<p style="color:red; font-weight:bold;">' . esc_html($error_msg) . '</p>';
	}

	$currentDate = date("d/m/Y H:i");
	$output .= '<div class="tm-main-header">';
	$output .= '<h2>Gestione Tavoli</h2>';
	$output .= '<div class="tm-date-header">' . $currentDate . '</div>';
	$output .= '</div>';

	if (isset($_GET['table_id'])) {
		$table_id = intval($_GET['table_id']);
		$table = $db->get_row("SELECT * FROM tavolo WHERE id = {$table_id}");
		$orders = $db->get_results("
			SELECT o.*, p.nome as prodotto_nome, o.id as order_id
			FROM ordini o
			INNER JOIN prodotti p ON o.prodotto_id = p.id
			WHERE o.tavolo_id = {$table_id}
		");
		$total = 0;
		if ($orders) {
			foreach ($orders as $ord) {
				$total += floatval($ord->prezzo) * intval($ord->quantita);
			}
		}
		echo '<script>var currentTableId = ' . $table_id . ';</script>';
		$output .= '<div class="tm-detail-container">';
		$output .= '<div class="tm-receipt" id="receiptContainer">';
		$output .= '<div class="tm-receipt-header" style="text-align:center;">';
		$output .= '<img src="https://gestione.pierbar.it/wp-content/uploads/2025/01/logo-pierbar.png" alt="Logo PierBar">';
		$output .= '</div>';
		$output .= '<div class="tm-receipt-address" style="text-align:center;">';
		$output .= 'Via dei colli 42<br>35143 Padova (Pd)<br>P.IVA 00122580285';
		$output .= '</div>';
		$ordine_num = $_SESSION['order_number'];
		$table_num  = $table ? $table->numero : '';
		$output .= '<div class="tm-receipt-subheader" style="text-align:center;">';
		$output .= 'Ordine - ' . $ordine_num . ' - Tavolo n°' . esc_html($table_num);
		$output .= '</div>';
		$output .= '<div style="margin:8px 0;"></div>';
		if ($orders) {
			foreach ($orders as $ord) {
				$qty = intval($ord->quantita);
				$price = floatval($ord->prezzo);
				$sum = $qty * $price;
				$descrizione = esc_html($ord->prodotto_nome) . ' x ' . $qty;
				$prezzoTesto = '€' . number_format($sum, 2);
				$output .= '<div class="tm-order-item" style="display:flex; justify-content:space-between; margin:2px 0; border-bottom:1px dashed #666;">';
				$output .= '<div style="text-align:left;">' . $descrizione . '</div>';
				$output .= '<div style="text-align:right;">' . $prezzoTesto . '</div>';
				$output .= '</div>';
			}
			$output .= '<div class="tm-total" style="text-align:right; margin-top:10px;">Totale: €' . number_format($total, 2) . '</div>';
		} else {
			$output .= '<p style="text-align:center;">Nessun prodotto acquistato.</p>';
		}
		$output .= '<div style="margin:8px 0;"></div>';
		$output .= '<div class="tm-date" style="text-align:center;">' . $currentDate . '</div>';
		$output .= '</div>';
		$output .= '<div class="tm-menu">';
		$output .= '<button onclick="window.location=\'' . esc_url(remove_query_arg("table_id")) . '\'">Torna indietro</button>';
		$output .= '<button onclick="openModal(\'categoryModal\')">Scegli categoria</button>';
		$output .= '<button onclick="if(confirm(\'Confermi di svuotare il tavolo?\')) clearOrder(' . $table_id . ');">Svuota tavolo</button>';
		$output .= '<button onclick="printReceipt(' . $table_id . ')">Stampa ordine</button>';
		$output .= '<button onclick="alert(\'Dividi ordine non implementato\')">Dividi ordine</button>';
		$output .= '<button onclick="sendToKitchen(' . $table_id . ')">Invia ordine cucina</button>';
		$output .= '</div>';
		$output .= '</div>';
	} else {
		if ($areas) {
			foreach ($areas as $area) {
				$output .= '<div class="tm-area-section">';
				$output .= '<div class="tm-area-header">';
				$output .= '<div class="tm-area-name">' . esc_html($area->nome) . '</div>';
				$output .= '<button class="tm-area-settings-btn" onclick="openAreaModal(' . intval($area->id) . ', \'' . esc_js($area->nome) . '\')">&#9881;</button>';
				$output .= '</div>';
				$output .= '<div style="margin:10px 0;">';
				$output .= '<button class="tm-insert-table-btn" onclick="openInsertTableModal(' . intval($area->id) . ')">Inserisci Tavolo</button>';
				$output .= '</div>';
				$output .= '<div class="tm-tables-row">';
				if (isset($tavoli_by_area[$area->id])) {
					foreach ($tavoli_by_area[$area->id] as $tv) {
						$total_cost = isset($ordini_by_table[$tv->id]) ? floatval($ordini_by_table[$tv->id]) : 0;
						$classe_tavolo = ($total_cost > 0) ? 'occupied' : 'free';
						$output .= '<div class="tm-table ' . $classe_tavolo . '" onclick="window.location=\''.add_query_arg("table_id", intval($tv->id)).'\'">';
						$output .= '<div>Numero: ' . esc_html($tv->numero) . '</div>';
						$output .= '<div>Costo: €' . number_format($total_cost, 2) . '</div>';
						$output .= '<button class="tm-table-settings-btn" onclick="event.stopPropagation(); openTableModal(' . intval($tv->id) . ', \'' . esc_js($tv->numero) . '\')">&#9881;</button>';
						$output .= '</div>';
					}
				} else {
					$output .= '<p>Nessun tavolo in questa area.</p>';
				}
				$output .= '</div>';
				$output .= '</div>';
			}
		} else {
			$output .= '<p>Nessuna area disponibile. Crea un\'area prima di inserire i tavoli.</p>';
		}
	}

	// Modal: Impostazioni Globali (crea area)
	$output .= '<div id="globalSettingsModal" class="tm-modal-overlay" style="display:none;">
		<div class="tm-modal">
			<h3>Crea Nuova Area</h3>
			<form method="POST">
				<input type="hidden" name="action" value="create_area">
				<input type="text" name="area_name" placeholder="Nome Nuova Area" required>
				<button type="submit">Crea Area</button>
			</form>
			<button class="tm-modal-close" onclick="closeModal(\'globalSettingsModal\')">Chiudi</button>
		</div>
	</div>';

	// Modal: Impostazioni Area (modifica/elimina)
	$output .= '<div id="areaSettingsModal" class="tm-modal-overlay" style="display:none;">
		<div class="tm-modal">
			<h3>Impostazioni Area</h3>
			<form method="POST">
				<input type="hidden" name="action" value="edit_area">
				<input type="hidden" name="area_id" id="editAreaId" value="">
				<input type="text" name="area_name" id="editAreaName" placeholder="Nuovo nome area" required>
				<button type="submit">Modifica Nome Area</button>
			</form>
			<form method="POST" style="margin-top:15px;">
				<input type="hidden" name="action" value="delete_area">
				<input type="hidden" name="area_id" id="deleteAreaId" value="">
				<button type="submit" style="background:#f44336;">Elimina Area</button>
			</form>
			<button class="tm-modal-close" onclick="closeModal(\'areaSettingsModal\')">Chiudi</button>
		</div>
	</div>';

	// Modal: Inserisci Tavolo
	$output .= '<div id="insertTableModal" class="tm-modal-overlay" style="display:none;">
		<div class="tm-modal">
			<h3>Inserisci Nuovo Tavolo</h3>
			<form method="POST">
				<input type="hidden" name="action" value="create_table">
				<input type="hidden" name="area_id" id="insertTableAreaId" value="">
				<input type="text" name="table_num" placeholder="Numero Tavolo" required>
				<button type="submit">Crea Tavolo</button>
			</form>
			<button class="tm-modal-close" onclick="closeModal(\'insertTableModal\')">Chiudi</button>
		</div>
	</div>';

	// Modal: Impostazioni Tavolo (modifica/elimina)
	$output .= '<div id="tableSettingsModal" class="tm-modal-overlay" style="display:none;">
		<div class="tm-modal">
			<h3>Impostazioni Tavolo</h3>
			<form method="POST">
				<input type="hidden" name="action" value="edit_table">
				<input type="hidden" name="table_id" id="editTableId" value="">
				<input type="text" name="table_num" id="editTableNum" placeholder="Nuovo Numero Tavolo" required>
				<button type="submit">Modifica Tavolo</button>
			</form>
			<form method="POST" style="margin-top:15px;">
				<input type="hidden" name="action" value="delete_table">
				<input type="hidden" name="table_id" id="deleteTableId" value="">
				<button type="submit" style="background:#f44336;">Elimina Tavolo</button>
			</form>
			<button class="tm-modal-close" onclick="closeModal(\'tableSettingsModal\')">Chiudi</button>
		</div>
	</div>';

	// Modal: Selezione Categoria/Prodotto
	$output .= '<div id="categoryModal" class="tm-modal-overlay" style="display:none;">
		<div class="tm-modal" id="categoryModalContent">
			<h3>Scegli Categoria</h3>
			<div id="categoryList">';
	$cats = $db->get_results("SELECT * FROM categorie ORDER BY nome ASC");
	if ($cats) {
		foreach ($cats as $cat) {
			$output .= '<button style="width:100%; margin-bottom:10px;" onclick="showProducts(' . intval($cat->id) . ')">' . esc_html($cat->nome) . '</button>';
		}
	}
	$output .= '	</div>
			<div id="productList" style="display:none;">
				<h3>Scegli Prodotto</h3>
				<div id="productsContainer"></div>
				<button style="width:100%; margin-top:10px;" onclick="backToCategories()">Indietro</button>
			</div>
			<button class="tm-modal-close" onclick="closeModal(\'categoryModal\')">Chiudi</button>
		</div>
	</div>';

	// Script JS per funzioni e gestione modali
	$output .= '<script>
		var allProducts = ' . json_encode($all_products) . ';
		function openModal(modalId) {
			document.getElementById(modalId).style.display = "flex";
		}
		function closeModal(modalId) {
			document.getElementById(modalId).style.display = "none";
		}
		function openAreaModal(areaId, areaName) {
			document.getElementById("editAreaId").value = areaId;
			document.getElementById("editAreaName").value = areaName;
			document.getElementById("deleteAreaId").value = areaId;
			openModal("areaSettingsModal");
		}
		function openInsertTableModal(areaId) {
			document.getElementById("insertTableAreaId").value = areaId;
			openModal("insertTableModal");
		}
		function openTableModal(tableId, tableNum) {
			document.getElementById("editTableId").value = tableId;
			document.getElementById("editTableNum").value = tableNum;
			document.getElementById("deleteTableId").value = tableId;
			openModal("tableSettingsModal");
		}
		function clearOrder(tableId) {
			if(confirm("Sei sicuro di svuotare il tavolo?")) {
				var f = document.createElement("form");
				f.method = "POST";
				f.style.display = "none";
				var i1 = document.createElement("input");
				i1.name = "action";
				i1.value = "clear_order";
				var i2 = document.createElement("input");
				i2.name = "table_id";
				i2.value = tableId;
				f.appendChild(i1);
				f.appendChild(i2);
				document.body.appendChild(f);
				f.submit();
			}
		}
		function deleteOrderItem(orderId, tableId) {
			if(confirm("Confermi di cancellare questo prodotto?")) {
				var f = document.createElement("form");
				f.method = "POST";
				f.style.display = "none";
				var i1 = document.createElement("input");
				i1.name = "action";
				i1.value = "delete_order";
				var i2 = document.createElement("input");
				i2.name = "order_id";
				i2.value = orderId;
				f.appendChild(i1);
				f.appendChild(i2);
				document.body.appendChild(f);
				f.submit();
			}
		}
		function printReceipt(tableId) {
			var rec = document.getElementById("receiptContainer").innerHTML;
			var w = window.open("", "", "width=400,height=600");
			w.document.write("<html><head><title>Scontrino Tavolo " + tableId + "</title>");
			w.document.write("<style> body { font-family: Impact, sans-serif; font-size:40px; font-weight:bold; line-height:1.3em; margin:0; padding:10px; width:300px; color:#000; } .tm-order-item button { display:none; } .tm-order-item { margin-bottom:5px; } img { width:4cm; display:block; margin:0 auto; } </style>");
			w.document.write("</head><body>");
			w.document.write(rec);
			w.document.write("</body></html>");
			w.document.close();
			w.focus();
			w.print();
			w.close();
		}
		function sendToKitchen(tableId) {
			if(confirm("Confermi di inviare l\'ordine a cucina (solo prodotti della categoria \'Cucina\')?")) {
				var f = document.createElement("form");
				f.method = "POST";
				f.style.display = "none";
				var i1 = document.createElement("input");
				i1.name = "action";
				i1.value = "invia_cucina";
				var i2 = document.createElement("input");
				i2.name = "table_id";
				i2.value = tableId;
				f.appendChild(i1);
				f.appendChild(i2);
				document.body.appendChild(f);
				f.submit();
			}
		}
		function showProducts(catId) {
			document.getElementById("categoryList").style.display = "none";
			document.getElementById("productList").style.display = "block";
			var container = document.getElementById("productsContainer");
			container.innerHTML = "";
			for(var i = 0; i < allProducts.length; i++){
				if(parseInt(allProducts[i].categoria_id) === catId){
					var box = document.createElement("div");
					box.className = "product-box";
					var nameEl = document.createElement("div");
					nameEl.className = "product-name";
					nameEl.textContent = allProducts[i].nome;
					var priceEl = document.createElement("div");
					priceEl.className = "product-price";
					priceEl.textContent = "€" + parseFloat(allProducts[i].prezzo).toFixed(2);
					box.appendChild(nameEl);
					box.appendChild(priceEl);
					(function(prodId){
						box.onclick = function(){
							addProductToOrder(prodId);
						};
					})(allProducts[i].id);
					container.appendChild(box);
				}
			}
		}
		function backToCategories() {
			document.getElementById("productList").style.display = "none";
			document.getElementById("categoryList").style.display = "block";
		}
		function addProductToOrder(productId) {
			if(typeof currentTableId === "undefined" || !currentTableId){
				alert("Nessun tavolo selezionato.");
				return;
			}
			var f = document.createElement("form");
			f.method = "POST";
			var a = document.createElement("input");
			a.name = "action";
			a.value = "create_order";
			var t = document.createElement("input");
			t.name = "table_id";
			t.value = currentTableId;
			var p = document.createElement("input");
			p.name = "prodotto_id";
			p.value = productId;
			var q = document.createElement("input");
			q.name = "quantita";
			q.value = 1;
			f.appendChild(a);
			f.appendChild(t);
			f.appendChild(p);
			f.appendChild(q);
			document.body.appendChild(f);
			f.submit();
		}
	</script>';

	$output .= '</div><!-- fine .tm-container -->';
	return $output;
}
add_shortcode("table_management", "get_table_management");

/* Abilita gli shortcode nei widget */
add_filter('widget_text', 'do_shortcode');
?>
