-- =========================================================================
-- Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
-- SPDX-License-Identifier: GPL-3.0-or-later
--
-- MokoDoliJoomShop - Local cache and mapping tables
-- Products and orders live in Dolibarr; these tables cache/map them.
-- =========================================================================

-- Cart items (session-based shopping cart)
CREATE TABLE IF NOT EXISTS `#__mokodolijoomshop_cart` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`session_id` varchar(255) NOT NULL,
	`user_id` int(10) unsigned NOT NULL DEFAULT 0,
	`dolibarr_product_id` int(11) NOT NULL,
	`product_ref` varchar(128) NOT NULL DEFAULT '',
	`product_label` varchar(255) NOT NULL DEFAULT '',
	`quantity` int(11) NOT NULL DEFAULT 1,
	`unit_price` decimal(12, 4) NOT NULL DEFAULT 0.0000,
	`tax_rate` decimal(5, 2) NOT NULL DEFAULT 0.00,
	`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	PRIMARY KEY (`id`),
	KEY `idx_session` (`session_id`),
	KEY `idx_user` (`user_id`),
	KEY `idx_product` (`dolibarr_product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Order mapping (links Joomla orders to Dolibarr orders/invoices)
CREATE TABLE IF NOT EXISTS `#__mokodolijoomshop_orders` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`user_id` int(10) unsigned NOT NULL DEFAULT 0,
	`dolibarr_order_id` int(11) DEFAULT NULL,
	`dolibarr_invoice_id` int(11) DEFAULT NULL,
	`dolibarr_thirdparty_id` int(11) DEFAULT NULL,
	`order_ref` varchar(128) NOT NULL DEFAULT '',
	`invoice_ref` varchar(128) NOT NULL DEFAULT '',
	`total_ht` decimal(12, 4) NOT NULL DEFAULT 0.0000,
	`total_ttc` decimal(12, 4) NOT NULL DEFAULT 0.0000,
	`status` varchar(20) NOT NULL DEFAULT 'pending',
	`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	PRIMARY KEY (`id`),
	KEY `idx_user` (`user_id`),
	KEY `idx_dolibarr_order` (`dolibarr_order_id`),
	KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Customer mapping (links Joomla users to Dolibarr thirdparties)
CREATE TABLE IF NOT EXISTS `#__mokodolijoomshop_customers` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`user_id` int(10) unsigned NOT NULL,
	`dolibarr_thirdparty_id` int(11) NOT NULL,
	`synced_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
	PRIMARY KEY (`id`),
	UNIQUE KEY `idx_user_unique` (`user_id`),
	KEY `idx_thirdparty` (`dolibarr_thirdparty_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
