-- Step 1 foundation for Eid Orders (طلبات العيد)
-- Adds Eid-specific tracking columns to the shared sales_orders table.

SET @db_name := DATABASE();

SET @sql := IF (
  EXISTS (
    SELECT 1 FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'sales_orders' AND COLUMN_NAME = 'order_type'
  ),
  'SELECT 1',
  "ALTER TABLE sales_orders ADD COLUMN order_type varchar(30) NOT NULL DEFAULT 'standard' AFTER status"
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := IF (
  EXISTS (
    SELECT 1 FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'sales_orders' AND COLUMN_NAME = 'delivery_status'
  ),
  'SELECT 1',
  "ALTER TABLE sales_orders ADD COLUMN delivery_status varchar(30) NOT NULL DEFAULT 'pending' AFTER order_type"
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := IF (
  EXISTS (
    SELECT 1 FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'sales_orders' AND COLUMN_NAME = 'delivery_date'
  ),
  'SELECT 1',
  "ALTER TABLE sales_orders ADD COLUMN delivery_date date DEFAULT NULL AFTER delivery_status"
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := IF (
  EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'sales_orders' AND INDEX_NAME = 'idx_order_type'
  ),
  'SELECT 1',
  "ALTER TABLE sales_orders ADD INDEX idx_order_type (order_type)"
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql := IF (
  EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'sales_orders' AND INDEX_NAME = 'idx_delivery_date'
  ),
  'SELECT 1',
  "ALTER TABLE sales_orders ADD INDEX idx_delivery_date (delivery_date)"
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

UPDATE sales_orders
SET order_type = 'standard'
WHERE order_type IS NULL OR order_type = '';

UPDATE sales_orders
SET delivery_status = CASE
  WHEN COALESCE(status, 'completed') = 'completed' THEN 'delivered'
  ELSE 'pending'
END
WHERE delivery_status IS NULL OR delivery_status = '';
