-- -----------------------------------------------------------
-- Internal GRN (Goods Receipt Note) - Factory to Warehouse
-- Records receipt of finished goods from factory to destination warehouse
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `internal_grns` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `grn_no` varchar(50) NOT NULL,
  `from_warehouse_id` int unsigned NOT NULL,
  `to_warehouse_id` int unsigned NOT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `internal_asn_id` int unsigned DEFAULT NULL,
  `dispatch_note_id` int unsigned DEFAULT NULL,
  `production_order_id` int unsigned DEFAULT NULL,
  `receipt_date` date DEFAULT NULL,
  `vehicle_no` varchar(100) DEFAULT NULL,
  `driver_name` varchar(255) DEFAULT NULL,
  `driver_phone` varchar(50) DEFAULT NULL,
  `transporter_name` varchar(255) DEFAULT NULL,
  `total_qty` decimal(14,4) DEFAULT 0,
  `total_cartons` int unsigned DEFAULT 0,
  `total_pallets` int unsigned DEFAULT NULL,
  `total_weight_kg` decimal(14,2) DEFAULT NULL,
  `total_volume_cbm` decimal(10,3) DEFAULT NULL,
  `shipping_marks` text,
  `notes` text,
  `status` enum('draft','received','cancelled') NOT NULL DEFAULT 'draft',
  `created_by` int unsigned DEFAULT NULL,
  `received_by` int unsigned 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 `uk_igrn_no` (`grn_no`, `company_id`),
  KEY `idx_igrn_status` (`status`),
  KEY `idx_igrn_company` (`company_id`),
  KEY `idx_igrn_from_wh` (`from_warehouse_id`),
  KEY `idx_igrn_to_wh` (`to_warehouse_id`),
  KEY `idx_igrn_iasn` (`internal_asn_id`),
  KEY `idx_igrn_factory` (`factory_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `internal_grn_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `lot_no` varchar(100) DEFAULT NULL,
  `batch_no` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned DEFAULT NULL,
  `received_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `accepted_qty` decimal(14,4) DEFAULT NULL,
  `rejected_qty` decimal(14,4) DEFAULT NULL,
  `cartons` int unsigned DEFAULT 0,
  `pallets` int unsigned DEFAULT NULL,
  `weight_kg` decimal(14,2) DEFAULT NULL,
  `volume_cbm` decimal(10,3) DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_igri_grn` (`grn_id`),
  KEY `idx_igri_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
