-- ============================================================
-- Migración 003 · orders (pedidos de la tienda de hosting)
-- ============================================================
-- Descripción:
--   Crea la tabla `orders` que guarda los pedidos realizados
--   desde la tienda de hosting (/tienda/hosting).
--
--   Guarda también el tipo de dominio seleccionado en el paso 1:
--     · register  → Registrar un dominio nuevo.
--     · transfer  → Transferir un nombre de dominio.
--     · existing  → Usar un nombre de dominio existente.
--
-- Uso:
--   1. Ve a phpMyAdmin → base `astrostudio_astrostudio` → pestaña "SQL".
--   2. Pega todo este contenido y pulsa "Continuar".
-- ============================================================

CREATE TABLE IF NOT EXISTS `orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `order_code` varchar(30) NOT NULL COMMENT 'Código de compra (ej: astro#491381)',
  `user_id` int unsigned DEFAULT NULL COMMENT 'Cliente (si inició sesión o se registró)',
  `plan_id` int unsigned NOT NULL COMMENT 'Plan de hosting elegido',
  `domain_name` varchar(255) NOT NULL COMMENT 'Dominio completo (ej: astrsads.com)',
  `domain_tld` varchar(20) NOT NULL COMMENT 'Extensión (ej: com, net, pe)',
  `domain_type` enum('register','transfer','existing') NOT NULL DEFAULT 'register' COMMENT 'Tipo de dominio seleccionado en el paso 1',
  `customer_name` varchar(150) DEFAULT NULL,
  `customer_email` varchar(150) DEFAULT NULL,
  `customer_phone` varchar(20) DEFAULT NULL,
  `payment_method` varchar(50) NOT NULL DEFAULT 'transfer_yape_plin',
  `notes` text DEFAULT NULL COMMENT 'Notas adicionales del cliente',
  `terms_accepted` tinyint(1) NOT NULL DEFAULT 0,
  `total` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'Total en soles',
  `billing_cycle` varchar(20) NOT NULL DEFAULT 'annual',
  `status` enum('pending_validation','confirmed','cancelled') NOT NULL DEFAULT 'pending_validation' COMMENT 'Pendiente de validación hasta recibir el pago',
  `client_ip` varchar(45) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `orders_order_code_unique` (`order_code`),
  KEY `orders_user_id_index` (`user_id`),
  KEY `orders_plan_id_index` (`plan_id`),
  CONSTRAINT `fk_orders_plan` FOREIGN KEY (`plan_id`) REFERENCES `plans` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;