CREATE TABLE `capa_root_causes` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `capa_id` INT UNSIGNED NOT NULL,
  `method` VARCHAR(50) NOT NULL COMMENT 'e.g. 5whys, fishbone, fmea',
  `root_cause` TEXT NOT NULL,
  `category` VARCHAR(100) DEFAULT NULL COMMENT 'man, machine, material, method, measurement, environment',
  `why_1` TEXT DEFAULT NULL,
  `why_2` TEXT DEFAULT NULL,
  `why_3` TEXT DEFAULT NULL,
  `why_4` TEXT DEFAULT NULL,
  `why_5` TEXT DEFAULT NULL,
  `ai_confidence` DECIMAL(5,2) DEFAULT NULL COMMENT 'AI suggestion confidence score',
  `created_by` INT UNSIGNED DEFAULT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_rca_capa` (`capa_id`),
  FOREIGN KEY (`capa_id`) REFERENCES `inspection_capa`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================
-- CAPA ACTIONS (individual corrective/preventive action items)
-- ========================
CREATE TABLE `capa_actions` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `capa_id` INT UNSIGNED NOT NULL,
  `action_type` ENUM('corrective','preventive') NOT NULL,
  `description` TEXT NOT NULL,
  `department` VARCHAR(100) DEFAULT NULL,
  `owner` VARCHAR(255) DEFAULT NULL,
  `start_date` DATE DEFAULT NULL,
  `deadline` DATE DEFAULT NULL,
  `priority` ENUM('high','medium','low') DEFAULT 'medium',
  `status` ENUM('pending','in_progress','completed','cancelled') NOT NULL DEFAULT 'pending',
  `completion_date` DATE DEFAULT NULL,
  `notes` TEXT DEFAULT NULL,
  `created_by` INT UNSIGNED DEFAULT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX `idx_action_capa` (`capa_id`),
  INDEX `idx_action_status` (`status`),
  FOREIGN KEY (`capa_id`) REFERENCES `inspection_capa`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================
-- CAPA VERIFICATION RECORDS
-- ========================
CREATE TABLE `capa_verifications` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `capa_id` INT UNSIGNED NOT NULL,
  `verification_type` ENUM('physical','process','statistical') NOT NULL DEFAULT 'physical',
  `verified_by` VARCHAR(255) DEFAULT NULL,
  `verification_date` DATE DEFAULT NULL,
  `method` VARCHAR(255) DEFAULT NULL,
  `criteria` TEXT DEFAULT NULL,
  `result` TEXT DEFAULT NULL,
  `effectiveness_score` INT DEFAULT NULL COMMENT '0-100',
  `defects_eliminated` TINYINT(1) DEFAULT 0,
  `rework_completed` TINYINT(1) DEFAULT 0,
  `sop_implemented` TINYINT(1) DEFAULT 0,
  `training_completed` TINYINT(1) DEFAULT 0,
  `before_value` VARCHAR(100) DEFAULT NULL COMMENT 'Statistical before value',
  `after_value` VARCHAR(100) DEFAULT NULL COMMENT 'Statistical after value',
  `improvement_pct` DECIMAL(5,1) DEFAULT NULL,
  `remarks` TEXT DEFAULT NULL,
  `created_by` INT UNSIGNED DEFAULT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_ver_capa` (`capa_id`),
  FOREIGN KEY (`capa_id`) REFERENCES `inspection_capa`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================
-- CAPA ATTACHMENTS
-- ========================
CREATE TABLE `capa_attachments` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `capa_id` INT UNSIGNED NOT NULL,
  `file_name` VARCHAR(255) NOT NULL,
  `file_type` ENUM('photo','document','video','other') NOT NULL DEFAULT 'document',
  `file_path` VARCHAR(500) DEFAULT NULL,
  `file_url` VARCHAR(500) DEFAULT NULL,
  `file_size` INT UNSIGNED DEFAULT NULL COMMENT 'Size in bytes',
  `mime_type` VARCHAR(100) DEFAULT NULL,
  `notes` TEXT DEFAULT NULL,
  `created_by` INT UNSIGNED DEFAULT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX `idx_att_capa` (`capa_id`),
  FOREIGN KEY (`capa_id`) REFERENCES `inspection_capa`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================
-- CAPA TASKS
-- ========================
CREATE TABLE `capa_tasks` (
  `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `capa_id` INT UNSIGNED NOT NULL,
  `title` VARCHAR(500) NOT NULL,
  `description` TEXT DEFAULT NULL,
  `assigned_to` INT UNSIGNED DEFAULT NULL,
  `department` VARCHAR(100) DEFAULT NULL,
  `start_date` DATE DEFAULT NULL,
  `deadline` DATE DEFAULT NULL,
  `priority` ENUM('high','medium','low') DEFAULT 'medium',
  `status` ENUM('pending','in_progress','completed','cancelled') NOT NULL DEFAULT 'pending',
  `completion_date` DATE DEFAULT NULL,
  `notes` TEXT DEFAULT NULL,
  `created_by` INT UNSIGNED DEFAULT NULL,
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX `idx_task_capa` (`capa_id`),
  INDEX `idx_task_assigned` (`assigned_to`),
  INDEX `idx_task_status` (`status`),
  FOREIGN KEY (`capa_id`) REFERENCES `inspection_capa`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;



-- ============================================================
-- FILE: seed_capa_advanced.sql
-- ============================================================

-- FCQC - Seed Dummy Data for Advanced CAPA System
-- Run AFTER migration_capa_advanced.sql and seed_qc_inspection.sql


-- ========================================================================
-- 1. CAPA MASTER RECORDS (extended inspection_capa)
-- ========================================================================
INSERT IGNORE INTO `inspection_capa` (`id`, `session_id`, `defect_id`, `capa_number`, `title`, `department`, `severity`, `source`, `root_cause`, `root_cause_category`, `corrective_action`, `preventive_action`, `containment_action`, `containment_responsible`, `containment_deadline`, `containment_completed_at`, `assigned_to`, `deadline`, `status`, `verification_method`, `verification_result`, `re_inspection_session_id`, `effectiveness_rating`, `effectiveness_review_date`, `closure_notes`, `lessons_learned`, `company_id`, `created_by`, `created_at`, `updated_at`) VALUES
(1, 1, 107, 'CAPA-2026-0001', 'Fabric shade variation exceeds acceptable range in PO-2026-001', 'Fabric Store', 'critical', 'inspection',
 'Incoming fabric rolls from supplier had inconsistent dye lots causing visible shade bands across the width.',
 'material',
 'Segregate affected rolls. Return 12 non-compliant rolls to supplier. Issue credit note.',
 'Implement 100% fabric inspection prior to spreading. Update supplier quality agreement with stricter shade tolerance clauses. Install spectrophotometer for digital shade assessment.',
 'Stop all spreading from affected batch. Quarantine 45 rolls. Inform production planning for re-cutting.',
 'Ahmed Hassan', '2026-06-20', '2026-06-19',
 2, '2026-06-30', 'closed', 'Re-inspection', 'All 12 returned rolls verified. Remaining 33 rolls tested with spectrophotometer — within tolerance. Production resumed.',
 NULL, 'effective', '2026-07-10',
 'CAPA closed successfully. Supplier accepted return and issued credit. Spectrophotometer ordered for receiving inspection.',
 'Always verify dye lot numbers before accepting fabric deliveries. Digital shade assessment eliminates human error in pass/fail decisions.',
 1, 1, '2026-06-18 09:30:00', '2026-07-10 14:00:00'),

(2, 1, 108, 'CAPA-2026-0002', 'Open seam defects on Style ST-102 exceeding DHU limit', 'Sewing', 'major', 'inspection',
 'Operators on Line 3 were running machines at excessive speed (4800 RPM vs standard 3800 RPM) causing skipped stitches and open seams. Needle size mismatch for fabric weight.',
 'process',
 'Rework 127 garments with open seams. Reset all machines on Line 3 to standard speed. Replace needles with correct size (DBx1 #14 for denim).',
 'Implement daily machine speed audit. Add needle size chart at each workstation. Mandatory pre-shift machine setup verification by line supervisor. Update SOP for style-specific machine settings.',
 'Stop Line 3 production. Segregate all output from last 2 hours. 100% inspection of 340 pieces.',
 'Fatima Begum', '2026-06-22', '2026-06-21',
 3, '2026-07-05', 'closed', 'Process Audit', 'Speed audit implemented. All 10 machines on Line 3 verified at correct settings. Operator retraining completed. Follow-up DHU check shows 1.2% (down from 8.3%).',
 NULL, 'effective', '2026-07-15',
 'All corrective and preventive actions completed. No recurrence of open seam defects on Line 3 for 10 consecutive production days.',
 'Machine speed control is critical for stitch quality. Needle size must be verified at every style changeover.',
 1, 1, '2026-06-20 11:00:00', '2026-07-15 16:30:00'),

(3, NULL, 150, 'CAPA-2026-0003', 'Customer complaint: Wrong labels attached to 500 pcs of Style ST-105', 'Finishing', 'critical', 'complaint',
 'Label packer on shift B used incorrect care labels (from previous style ST-102) due to poor label segregation at the trimming station. No verification step between label attachment and carton packing.',
 'process',
 'Contact customer, arrange for courier collection of 500 mislabeled pieces. Re-label all pieces with correct labels. Provide 15% discount on next order as goodwill.',
 'Implement two-person verification at label attachment station. Install barcode scanner to verify label vs style before attachment. Segregate label bundles per style in color-coded bins. Add label check step to end-of-line QA checklist.',
 'Quarantine all finished goods of style ST-105. 100% inspection of 1,200 cartons. Separate correctly labeled vs incorrectly labeled.',
 'Rafiq Uddin', '2026-06-25', '2026-06-24',
 4, '2026-07-10', 'closed', 'Physical Verification', 'All 1,200 cartons inspected. 500 pieces re-labeled. Customer accepted return arrangement. Barcode system ordered.',
 NULL, 'effective', '2026-07-20',
 'Customer complaint resolved. Discount provided. Barcode verification system installed and operational. No further label complaints in 3 weeks.',
 'Label verification needs a physical check step — barcode scanning prevents human error. Color-coded bins eliminate mix-ups during style changes.',
 1, 2, '2026-06-22 08:45:00', '2026-07-20 11:00:00'),

(4, NULL, 141, 'CAPA-2026-0004', 'Broken needle found in finished garment during final inspection', 'Sewing', 'critical', 'needle_breakage',
 'Needle broke during sewing of heavy seam intersection (style ST-108, pocket attachment). Operator did not notice breakage and continued sewing. Needle fragment embedded in garment seam.',
 'machine',
 '100% metal detection of all pieces from this style (2,400 pcs). Isolate and quarantine any additional finds. Document incident for insurance.',
 'Implement mandatory needle count procedure at shift start/end for all operators. Install needle detector machines at end of each sewing line. Replace all needles after 8 hours of use (needle replacement policy). Update training on needle breakage protocol.',
 'Stop all sewing for style ST-108. Initiate full metal detection sweep of Line 5 output for last 4 hours. Inform quality manager and production head immediately.',
 'Kamal Hossain', '2026-06-23', '2026-06-23',
 2, '2026-07-01', 'in_progress', NULL, NULL,
 NULL, NULL, NULL,
 'Immediate containment completed. Needle found and removed. Needle detector machines ordered — installation expected next week.',
 'Broken needle incidents require zero tolerance. Needle count policy and detector machines are essential for safety compliance.',
 1, 1, '2026-06-22 14:30:00', '2026-06-28 09:00:00'),

(5, NULL, NULL, 'CAPA-2026-0005', 'Supplier delivery delay causing production line stoppage', 'Production', 'major', 'supplier',
 'Supplier XYZ Trims failed to deliver zippers for style ST-112 on agreed date. No safety stock maintained. Alternative supplier not qualified.',
 'method',
 'Expedite delivery from XYZ with air freight at supplier cost. Source 5,000 zippers from local market as interim measure.',
 'Maintain 2 weeks safety stock for all critical trims. Qualify alternative supplier (ABC Trims) as backup. Implement weekly supplier delivery tracker with automatic escalation at 3 days before deadline.',
 'Stop trimming station for style ST-112. Reallocate operators to alternate styles. Place urgent order with XYZ and local market.',
 'Shamim Reza', '2026-06-26', '2026-06-25',
 NULL, '2026-07-15', 'open', NULL, NULL,
 NULL, NULL, NULL,
 NULL,
 NULL,
 1, 2, '2026-06-24 10:00:00', '2026-06-24 10:00:00'),

(6, 2, 102, 'CAPA-2026-0006', 'AQL rejection on End-Line inspection - Major defects exceed acceptance limit', 'QA', 'major', 'inspection',
 'Lot size 3,200 pcs, sample size 200 pcs. Found 21 major defects (Accept = 14, Reject = 21). Root cause traced to untrained operators on 2 new sewing machines added for capacity increase.',
 'training',
 '100% inspection of entire lot. Rework all defective garments. Segregate and quarantine.',
 'Implement mandatory operator training program before assigning to new machines. Extend training period from 2 days to 5 days. Add skill certification test before allowing independent work.',
 'Hold entire lot for inspection. Do not ship until rework completed and verified.',
 'Quality Manager', '2026-06-28', '2026-06-27',
 3, '2026-07-20', 'open', NULL, NULL,
 NULL, NULL, NULL,
 NULL,
 NULL,
 1, 1, '2026-06-26 16:00:00', '2026-06-26 16:00:00'),

(7, NULL, 113, 'CAPA-2026-0007', 'Print misregistration on 800 pcs - Style ST-115', 'Printing', 'major', 'inspection',
 'Screen tension on Frame #3 dropped below specification. Operator did not check tension before starting production run. First 800 pieces had 3mm misregistration on left chest print.',
 'machine',
 'Strip and reprint all 800 pieces. Replace screen on Frame #3. Retension all screens (daily check).',
 'Implement screen tension check as mandatory pre-production step. Add tension gauge at each screen printing station. Create screen tension log sheet with sign-off.',
 'Stop all printing on Frame #3. Quarantine all pieces from current run. Inspect all printed stock from last 4 hours.',
 'Shahidul Islam', '2026-06-29', '2026-06-28',
 5, '2026-07-12', 'in_progress', NULL, NULL,
 NULL, NULL, NULL,
 NULL, NULL,
 1, 1, '2026-06-27 09:15:00', '2026-06-28 11:00:00'),

(8, NULL, NULL, 'CAPA-2026-0008', 'Safety incident: Chemical splash during garment washing', 'Washing', 'critical', 'safety_incident',
 'Operator was not wearing proper PPE while handling caustic soda. Splash guard on dosing pump was damaged. No emergency shower accessible within 10 meters of chemical station.',
 'environment',
 'Immediate first aid for affected operator. Repair splash guard. Install emergency shower at chemical station. Provide full PPE kit to all washing operators.',
 'Monthly PPE compliance audit. Install chemical handling SOP poster at each station. Conduct quarterly safety training for all washing department staff. Implement chemical handling permit system.',
 'Stop all chemical handling operations until safety review completed. Restricted access to chemical storage area.',
 'Safety Officer', '2026-06-28', '2026-06-29',
 4, '2026-07-15', 'in_progress', NULL, NULL,
 NULL, NULL, NULL,
 NULL, NULL,
 1, 2, '2026-06-27 11:30:00', '2026-06-29 08:00:00'),

(9, NULL, 148, 'CAPA-2026-0009', 'Incorrect quantity packed in cartons - Customer claims shortage', 'Packing', 'critical', 'return',
 'Packing operators were not counting pieces before carton sealing. Verified quantity per carton should be 12 pcs but found cartons with 10, 11, and 13 pcs. No barcode scan verification at carton level.',
 'method',
 'Open and recount all 400 cartons from this order. Adjust packing documents. Send corrected packing list to customer.',
 'Implement barcode scanning at carton sealing station. Each carton must scan all 12 pieces before sealing. Add random weight check every 10th carton.',
 'Stop further shipments of this style. Recount all packed cartons in warehouse.',
 'Nurul Islam', '2026-06-30', '2026-06-29',
 NULL, '2026-07-20', 'open', NULL, NULL,
 NULL, NULL, NULL,
 NULL, NULL,
 1, 1, '2026-06-28 15:00:00', '2026-06-28 15:00:00'),

(10, NULL, 107, 'CAPA-2026-0010', 'Fabric pilling after 3 washes - Buyer complaint on Style ST-120', 'Fabric Store', 'minor', 'complaint',
 'Fabric supplier changed fiber composition without informing. Polyester content was 45% instead of specified 50%, causing reduced abrasion resistance.',
 'material',
 'Provide test reports to buyer showing current fabric composition. Offer discounted price for affected lot. Source replacement fabric from alternative supplier.',
 'Update supplier approval process to require composition testing certificate with every batch. Implement random fiber composition testing on incoming fabric (1 per 10 rolls). Blacklist supplier for 6 months.',
 'Quarantine all remaining fabric rolls of this lot. Separate finished goods for buyer review.',
 'Fabric Manager', '2026-07-05', '2026-07-03',
 NULL, '2026-08-15', 'open', NULL, NULL,
 NULL, NULL, NULL,
 NULL, NULL,
 1, 2, '2026-07-01 09:00:00', '2026-07-03 12:00:00');

-- ========================================================================
-- 2. CAPA ROOT CAUSES (multiple RCA analyses per CAPA)
-- ========================================================================
INSERT IGNORE INTO `capa_root_causes` (`id`, `capa_id`, `method`, `root_cause`, `category`, `why_1`, `why_2`, `why_3`, `why_4`, `why_5`, `ai_confidence`) VALUES
(1, 1, '5whys', 'No incoming fabric shade inspection process', 'method',
 'Shade variation found during spreading',
 'Receiving inspection only checks width and length, not shade',
 'No spectrophotometer available at receiving',
 'Equipment not budgeted for current fiscal year',
 'Management unaware of severity of past shade issues',
 78.50),
(2, 2, '5whys', 'No standard machine speed settings for different fabric types', 'method',
 'Open seams appearing on heavy fabric',
 'Operator increased machine speed to meet target',
 'No speed limit set for different fabric weights',
 'Machine settings not documented in SOP',
 'No process ownership for machine parameter standardization',
 82.30),
(3, 2, 'fishbone', 'Multiple factors contributing to open seam defects', 'method', NULL, NULL, NULL, NULL, NULL, 65.00),
(4, 3, '5whys', 'No label verification step between attachment and packing', 'process',
 'Wrong labels attached to garments',
 'Label packer grabbed wrong bundle',
 'Labels from previous style not cleared from station',
 'No standard procedure for style changeover label clearance',
 'Label verification not included in end-of-line checklist',
 91.20),
(5, 4, '5whys', 'No mandatory needle count procedure', 'machine',
 'Needle broke and operator did not notice',
 'Operator could not detect breakage during sewing',
 'No needle count check at start/end of shift',
 'Needle control policy not established',
 'Management focus on production speed over safety',
 95.00),
(6, 6, '5whys', 'Inadequate operator training period for new machines', 'training',
 'New operators on new machines producing high defect rate',
 'Operators assigned to machines after only 2 days training',
 'Training period reduced to meet production deadlines',
 'Production pressure overriding quality requirements',
 'No formal training curriculum for new machine operators',
 87.60);

-- ========================================================================
-- 3. CAPA ACTIONS (corrective and preventive action items)
-- ========================================================================
INSERT IGNORE INTO `capa_actions` (`id`, `capa_id`, `action_type`, `description`, `department`, `owner`, `start_date`, `deadline`, `priority`, `status`, `completion_date`, `notes`) VALUES
(1, 1, 'corrective', 'Segregate and grade all affected fabric rolls by shade band', 'Fabric Store', 'Store Keeper', '2026-06-19', '2026-06-21', 'high', 'completed', '2026-06-20', '12 rolls graded as reject, 33 rolls graded as acceptable with shade grouping'),
(2, 1, 'corrective', 'Return 12 non-compliant rolls to supplier with debit note', 'Purchase', 'Purchase Manager', '2026-06-21', '2026-06-28', 'high', 'completed', '2026-06-26', 'Supplier accepted return and issued credit note CR-2026-089'),
(3, 1, 'preventive', 'Implement spectrophotometer-based incoming fabric shade inspection', 'Fabric Store', 'QA Manager', '2026-07-01', '2026-08-15', 'high', 'in_progress', NULL, 'Spectrophotometer ordered (PO-2026-045). Expected delivery second week of August.'),
(4, 1, 'preventive', 'Update supplier quality agreement with stricter shade tolerance clause', 'Purchase', 'Purchase Manager', '2026-06-28', '2026-07-10', 'medium', 'completed', '2026-07-08', 'New shade tolerance clause added to all fabric supplier agreements'),
(5, 2, 'corrective', 'Rework all 127 garments with open seams', 'Sewing', 'Line Supervisor', '2026-06-21', '2026-06-23', 'high', 'completed', '2026-06-22', 'All 127 pieces reworked and inspected. Zero defects on re-inspection.'),
(6, 2, 'corrective', 'Reset and calibrate all machines on Line 3 to standard speed', 'Maintenance', 'Maintenance Tech', '2026-06-21', '2026-06-21', 'high', 'completed', '2026-06-21', 'All 10 machines calibrated. Speed governors installed.'),
(7, 2, 'preventive', 'Implement daily machine speed audit checklist', 'Sewing', 'Quality Inspector', '2026-06-22', NULL, 'medium', 'completed', '2026-06-22', 'Daily audit form created and posted at Line 3. Audits started.'),
(8, 2, 'preventive', 'Create machine parameter reference chart per style', 'Industrial Eng', 'IE Manager', '2026-06-22', '2026-07-01', 'high', 'completed', '2026-06-29', 'Reference charts created for top 20 styles. Laminated and posted at each workstation.'),
(9, 3, 'corrective', 'Contact customer and arrange return of 500 mislabeled pieces', 'Sales', 'Sales Manager', '2026-06-23', '2026-06-25', 'high', 'completed', '2026-06-24', 'Customer agreed to return via courier. Discount of 15% offered and accepted.'),
(10, 3, 'corrective', 'Re-label all 500 pieces with correct care labels', 'Finishing', 'Finishing Supervisor', '2026-06-25', '2026-06-28', 'high', 'completed', '2026-06-27', 'All 500 pieces re-labeled and packed. 100% verified.'),
(11, 3, 'preventive', 'Install barcode verification system at label attachment station', 'IT', 'IT Manager', '2026-07-01', '2026-07-15', 'high', 'completed', '2026-07-12', 'Barcode scanners installed. Integration with label printer completed.'),
(12, 3, 'preventive', 'Implement two-person verification at label attachment', 'Finishing', 'QA Manager', '2026-06-28', '2026-07-05', 'medium', 'completed', '2026-07-03', 'Standard procedure updated. Staff trained on new process.'),
(13, 4, 'corrective', '100% metal detection of all 2,400 pieces from affected lot', 'QA', 'QA Inspector', '2026-06-23', '2026-06-24', 'high', 'completed', '2026-06-24', 'All pieces scanned. No additional needles found.'),
(14, 4, 'preventive', 'Implement needle count policy at shift start and end', 'Sewing', 'Production Manager', '2026-06-24', '2026-06-28', 'high', 'completed', '2026-06-27', 'Needle count register created. Policy implemented across all sewing lines.'),
(15, 4, 'preventive', 'Install needle detector machines on all sewing lines', 'Maintenance', 'Engineering Head', '2026-07-01', '2026-08-01', 'high', 'in_progress', NULL, '3 machines ordered. Installation of first machine scheduled for next week.'),
(16, 6, 'corrective', '100% inspection of entire lot (3,200 pcs)', 'QA', 'QA Team Lead', '2026-06-27', '2026-07-02', 'high', 'completed', '2026-07-01', 'Lot fully inspected. 87 pieces reworked. Lot released.'),
(17, 6, 'preventive', 'Develop operator training curriculum for new machines', 'HR', 'Training Manager', '2026-07-01', '2026-07-15', 'high', 'completed', '2026-07-14', '5-day training program developed. Includes theory, practical, and certification test.'),
(18, 8, 'corrective', 'Repair chemical splash guard on dosing pump', 'Maintenance', 'Maintenance Team', '2026-06-28', '2026-06-29', 'high', 'completed', '2026-06-29', 'Splash guard repaired and reinforced.'),
(19, 8, 'corrective', 'Install emergency shower near chemical station', 'Engineering', 'Engineering Head', '2026-06-28', '2026-07-05', 'high', 'completed', '2026-07-04', 'Emergency shower installed and tested. Meets safety distance requirement.'),
(20, 8, 'preventive', 'Conduct monthly PPE compliance audit', 'Safety', 'Safety Officer', '2026-07-01', NULL, 'medium', 'in_progress', NULL, 'First audit scheduled for July 15.');

-- ========================================================================
-- 4. CAPA TASKS
-- ========================================================================
INSERT IGNORE INTO `capa_tasks` (`id`, `capa_id`, `title`, `description`, `assigned_to`, `department`, `start_date`, `deadline`, `priority`, `status`, `completion_date`, `notes`) VALUES
(1, 1, 'Grade fabric rolls by shade', 'Visually grade all 45 fabric rolls into shade groups A, B, C', 5, 'Fabric Store', '2026-06-19', '2026-06-20', 'high', 'completed', '2026-06-19', 'Completed. 12 rolls in group C (reject).'),
(2, 1, 'Prepare debit note for supplier', 'Create debit note for 12 rejected fabric rolls', 6, 'Purchase', '2026-06-21', '2026-06-22', 'high', 'completed', '2026-06-21', 'Debit note DN-2026-034 sent to supplier.'),
(3, 1, 'Order spectrophotometer', 'Research and place purchase order for spectrophotometer', 7, 'QA', '2026-07-01', '2026-07-10', 'high', 'completed', '2026-07-08', 'Spectrophotometer ordered. Model: X-Rite CE-7000A. Delivery: Aug 15.'),
(4, 2, 'Rework open seam garments', 'Re-stitch all 127 garments with open seams', 8, 'Sewing', '2026-06-21', '2026-06-23', 'high', 'completed', '2026-06-22', 'All rework completed.'),
(5, 2, 'Calibrate machine speeds', 'Reset all 10 machines on Line 3 to standard 3800 RPM', 9, 'Maintenance', '2026-06-21', '2026-06-21', 'high', 'completed', '2026-06-21', 'All machines calibrated and speed governors installed.'),
(6, 2, 'Create style parameter charts', 'Document correct machine settings for top 20 styles', 10, 'IE', '2026-06-22', '2026-06-29', 'medium', 'completed', '2026-06-28', 'Charts created and laminated.'),
(7, 3, 'Arrange customer return', 'Contact customer and arrange courier for 500 pieces', 11, 'Sales', '2026-06-23', '2026-06-24', 'high', 'completed', '2026-06-23', 'Customer return arranged.'),
(8, 3, 'Re-label 500 garments', 'Remove incorrect labels and attach correct care labels', 8, 'Finishing', '2026-06-25', '2026-06-27', 'high', 'completed', '2026-06-26', 'All re-labeled and verified.'),
(9, 3, 'Install barcode scanners at label stations', 'Set up barcode verification system for label attachment verification', 12, 'IT', '2026-07-01', '2026-07-12', 'high', 'completed', '2026-07-10', 'System installed and tested.'),
(10, 4, 'Scan all 2,400 pieces with metal detector', 'Run all pieces from affected lot through needle detector machine', 13, 'QA', '2026-06-23', '2026-06-24', 'high', 'completed', '2026-06-24', 'All pieces scanned. No additional needles.'),
(11, 4, 'Create needle count register', 'Design and print needle count log sheets for all sewing lines', 14, 'Production', '2026-06-24', '2026-06-26', 'high', 'completed', '2026-06-25', 'Register created. Distributed to all lines.'),
(12, 6, 'Inspect entire lot 100%', 'Full inspection of 3,200 pieces from rejected lot', 13, 'QA', '2026-06-27', '2026-07-01', 'high', 'completed', '2026-06-30', '87 pieces sent for rework. Lot released after re-inspection.'),
(13, 6, 'Develop training program', 'Create 5-day training curriculum for new machine operators', 15, 'HR', '2026-07-01', '2026-07-14', 'high', 'completed', '2026-07-12', 'Curriculum developed and approved.');

-- ========================================================================
-- 5. CAPA VERIFICATIONS
-- ========================================================================
INSERT IGNORE INTO `capa_verifications` (`id`, `capa_id`, `verification_type`, `verified_by`, `verification_date`, `method`, `criteria`, `result`, `effectiveness_score`, `defects_eliminated`, `rework_completed`, `sop_implemented`, `training_completed`, `before_value`, `after_value`, `improvement_pct`, `remarks`) VALUES
(1, 1, 'physical', 'QA Manager', '2026-07-08', 'Re-inspection of 33 accepted rolls using spectrophotometer', 'All rolls must be within Delta E < 1.0 of standard', 'All 33 rolls measured. Max Delta E = 0.82. Average Delta E = 0.45.', 95, 1, 1, 1, 1, 'Shade rejection rate: 12/45 (26.7%)', 'Shade rejection rate with new process: 0/33 (0%)', 100.0, 'Spectrophotometer verification confirms complete elimination of shade variation issue.'),
(2, 2, 'statistical', 'Quality Inspector', '2026-07-10', 'DHU tracking on Line 3 for 10 production days post-CAPA', 'DHU must be below 3% (target 2%)', 'DHU averaged 1.2% over 10 days. Range: 0.8% - 1.8%.', 90, 1, 1, 1, 1, 'DHU before: 8.3%', 'DHU after: 1.2%', 85.5, 'Open seam defects virtually eliminated. Machine speed audit operating effectively.'),
(3, 3, 'physical', 'QA Team Lead', '2026-07-15', 'Random audit of 100 cartons from 5 production days', 'Zero label defects found in audit sample', '100 cartons checked. All labels correct. Barcode system functioning.', 98, 1, 1, 1, 1, 'Label defect rate: 500/1200 (41.7%)', 'Label defect rate: 0/100 (0%)', 100.0, 'Barcode system and two-person verification working effectively.'),
(4, 4, 'statistical', 'Safety Officer', '2026-06-28', 'Needle count compliance check on all sewing lines', '100% compliance on needle count procedure', '8 out of 8 sewing lines compliant. Needle registers properly maintained.', 85, 1, 1, 0, 1, 'Needle incidents: 1 per month avg', 'Needle incidents since CAPA: 0', 100.0, 'Needle count procedure fully implemented. Detector machines pending installation.');

-- ========================================================================
-- 6. CAPA ATTACHMENTS
-- ========================================================================
INSERT IGNORE INTO `capa_attachments` (`id`, `capa_id`, `file_name`, `file_type`, `file_path`, `file_url`, `file_size`, `mime_type`, `notes`) VALUES
(1, 1, 'shade_variation_report.pdf', 'document', '/uploads/capa/CAPA-1-shade-report.pdf', '/uploads/capa/CAPA-1-shade-report.pdf', 245760, 'application/pdf', 'Spectrophotometer reading report for all 45 rolls'),
(2, 1, 'supplier_credit_note.pdf', 'document', '/uploads/capa/CAPA-1-credit-note.pdf', '/uploads/capa/CAPA-1-credit-note.pdf', 102400, 'application/pdf', 'Credit note CR-2026-089 from supplier'),
(3, 2, 'open_seam_defect_photo.jpg', 'photo', '/uploads/capa/CAPA-2-defect-photo.jpg', '/uploads/capa/CAPA-2-defect-photo.jpg', 512000, 'image/jpeg', 'Typical open seam defect found on Line 3'),
(4, 2, 'machine_speed_audit_form.pdf', 'document', '/uploads/capa/CAPA-2-speed-audit.pdf', '/uploads/capa/CAPA-2-speed-audit.pdf', 81920, 'application/pdf', 'Daily machine speed audit checklist template'),
(5, 3, 'customer_complaint_email.pdf', 'document', '/uploads/capa/CAPA-3-complaint-email.pdf', '/uploads/capa/CAPA-3-complaint-email.pdf', 65536, 'application/pdf', 'Original customer complaint email'),
(6, 3, 'correct_label_photo.jpg', 'photo', '/uploads/capa/CAPA-3-correct-label.jpg', '/uploads/capa/CAPA-3-correct-label.jpg', 384000, 'image/jpeg', 'Correct label placement verification'),
(7, 4, 'incident_report.pdf', 'document', '/uploads/capa/CAPA-4-incident-report.pdf', '/uploads/capa/CAPA-4-incident-report.pdf', 163840, 'application/pdf', 'Needle breakage incident report form'),
(8, 8, 'emergency_shower_installation.jpg', 'photo', '/uploads/capa/CAPA-8-emergency-shower.jpg', '/uploads/capa/CAPA-8-emergency-shower.jpg', 720896, 'image/jpeg', 'Emergency shower installed near chemical station'),
(9, 8, 'ppe_compliance_checklist.pdf', 'document', '/uploads/capa/CAPA-8-PPE-checklist.pdf', '/uploads/capa/CAPA-8-PPE-checklist.pdf', 45056, 'application/pdf', 'Monthly PPE compliance audit checklist template');



-- ============================================================
-- FILE: migration_checklist_items.sql
-- ============================================================

CREATE TABLE IF NOT EXISTS `inspection_checklist_items` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `session_id` INT UNSIGNED NOT NULL,
  `section_label` VARCHAR(255) DEFAULT NULL,
  `item_text` TEXT NOT NULL,
  `item_type` ENUM('yes_no','rating','text','observation') NOT NULL DEFAULT 'yes_no',
  `status` ENUM('pass','fail','na','pending') NOT NULL DEFAULT 'pending',
  `answer_value` VARCHAR(500) DEFAULT NULL,
  `answer_score` DECIMAL(5,2) DEFAULT NULL,
  `finding` TEXT DEFAULT NULL,
  `notes` TEXT DEFAULT NULL,
  `photo_url` VARCHAR(500) DEFAULT NULL,
  `item_order` INT NOT NULL DEFAULT 0,
  `is_mandatory` TINYINT(1) NOT NULL DEFAULT 0,
  `severity` ENUM('critical','major','minor','observation') DEFAULT NULL,
  `created_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`),
  KEY `idx_session` (`session_id`),
  CONSTRAINT `fk_checklist_session` FOREIGN KEY (`session_id`) REFERENCES `inspection_sessions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: migration_alter_inspection_photos.sql
-- ============================================================

ALTER TABLE `inspection_photos`
  ADD COLUMN `checklist_item_id` INT UNSIGNED DEFAULT NULL AFTER `field_key`,
  ADD KEY `idx_checklist_item` (`checklist_item_id`);


-- ============================================================
-- FILE: migration_procurement.sql
-- ============================================================

-- ============================================================
-- FashCognitive - AI-Driven Material Planning & Procurement
-- Core Schema: Indent -> Stock Allocation -> PR -> PO -> GRN
-- ============================================================

-- -----------------------------------------------------------
-- 1. WAREHOUSES
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `warehouses` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `factory_id` int unsigned DEFAULT NULL,
  `name` varchar(255) NOT NULL,
  `code` varchar(50) DEFAULT NULL,
  `address` text,
  `is_default` tinyint(1) NOT NULL DEFAULT 0,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_wh_factory` (`factory_id`),
  KEY `idx_wh_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 2. WAREHOUSE LOCATIONS (Rack > Shelf > Bin)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `warehouse_locations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `warehouse_id` int unsigned NOT NULL,
  `code` varchar(100) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `rack` varchar(50) DEFAULT NULL,
  `shelf` varchar(50) DEFAULT NULL,
  `bin` varchar(50) DEFAULT NULL,
  `capacity` decimal(14,4) DEFAULT NULL,
  `uom_id` int unsigned DEFAULT NULL,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_wl_warehouse` (`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 3. WAREHOUSE STOCK (current inventory per item per warehouse per lot)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `warehouse_stock` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `warehouse_id` int unsigned NOT NULL,
  `location_id` int unsigned DEFAULT 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,
  `supplier_id` int unsigned DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `qty` decimal(14,4) NOT NULL DEFAULT 0,
  `reserved_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `blocked_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `unit_cost` decimal(14,4) DEFAULT NULL,
  `currency_id` int unsigned DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `grn_id` int unsigned DEFAULT NULL,
  `status` enum('available','reserved','blocked','expired') NOT NULL DEFAULT 'available',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ws_warehouse` (`warehouse_id`),
  KEY `idx_ws_item` (`item_id`),
  KEY `idx_ws_company` (`company_id`),
  KEY `idx_ws_lot` (`lot_no`),
  KEY `idx_ws_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 4. STOCK LEDGER (every movement goes through here)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `stock_ledger` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `warehouse_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 NOT NULL,
  `movement_type` enum('purchase_in','transfer_in','transfer_out','issue','return','adjustment','consumption','qc_hold','qc_release','reservation','unreservation') NOT NULL,
  `qty_in` decimal(14,4) DEFAULT 0,
  `qty_out` decimal(14,4) DEFAULT 0,
  `balance` decimal(14,4) NOT NULL DEFAULT 0,
  `unit_cost` decimal(14,4) DEFAULT NULL,
  `reference_type` varchar(50) DEFAULT NULL,
  `reference_id` int unsigned DEFAULT NULL,
  `reference_no` varchar(100) DEFAULT NULL,
  `notes` text,
  `created_by` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_sl_warehouse` (`warehouse_id`),
  KEY `idx_sl_item` (`item_id`),
  KEY `idx_sl_movement` (`movement_type`),
  KEY `idx_sl_reference` (`reference_type`, `reference_id`),
  KEY `idx_sl_company` (`company_id`),
  KEY `idx_sl_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 5. STOCK RESERVATIONS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `stock_reservations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `stock_id` int unsigned NOT NULL,
  `size_master_id` int unsigned DEFAULT NULL,
  `reserved_qty` decimal(14,4) NOT NULL,
  `reserved_for_type` varchar(50) NOT NULL,
  `reserved_for_id` int unsigned NOT NULL,
  `reserved_for_no` varchar(100) DEFAULT NULL,
  `status` enum('active','fulfilled','cancelled') NOT NULL DEFAULT 'active',
  `reserved_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`),
  KEY `idx_sr_stock` (`stock_id`),
  KEY `idx_sr_status` (`status`),
  KEY `idx_sr_reference` (`reserved_for_type`, `reserved_for_id`),
  KEY `size_master_id` (`size_master_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 6. MATERIAL INDENTS (the heart of procurement)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `material_indents` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `indent_no` varchar(50) NOT NULL,
  `indent_type` enum('production','sampling','development','general_purchase','asset','maintenance','office_supplies','capex') NOT NULL DEFAULT 'production',
  `po_id` int unsigned DEFAULT NULL,
  `buyer_id` int unsigned DEFAULT NULL,
  `style_id` int unsigned DEFAULT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `warehouse_id` int unsigned DEFAULT NULL,
  `required_date` date NOT NULL,
  `priority` enum('low','medium','high','urgent') NOT NULL DEFAULT 'medium',
  `requested_by` int unsigned DEFAULT NULL,
  `department_id` int unsigned DEFAULT NULL,
  `status` enum('draft','pending_approval','approved','partially_fulfilled','fully_fulfilled','rejected','cancelled') NOT NULL DEFAULT 'draft',
  `ai_allocation_done` tinyint(1) NOT NULL DEFAULT 0,
  `notes` text,
  `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_indent_no` (`indent_no`, `company_id`),
  KEY `idx_mi_po` (`po_id`),
  KEY `idx_mi_factory` (`factory_id`),
  KEY `idx_mi_status` (`status`),
  KEY `idx_mi_company` (`company_id`),
  KEY `idx_mi_date` (`required_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 7. MATERIAL INDENT ITEMS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `material_indent_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `indent_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `required_qty` decimal(14,4) NOT NULL,
  `allocated_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `issued_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `status` enum('pending','allocated','partially_issued','fully_issued','cancelled') NOT NULL DEFAULT 'pending',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_mii_indent` (`indent_id`),
  KEY `idx_mii_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 8. INDENT ALLOCATIONS (AI stock allocation results)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `indent_allocations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `indent_item_id` int unsigned NOT NULL,
  `allocation_type` enum('warehouse_issue','warehouse_transfer','purchase_requisition') NOT NULL,
  `source_warehouse_id` int unsigned DEFAULT NULL,
  `target_warehouse_id` int unsigned DEFAULT NULL,
  `stock_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned DEFAULT NULL,
  `qty` decimal(14,4) NOT NULL,
  `unit_cost` decimal(14,4) DEFAULT NULL,
  `status` enum('pending','approved','fulfilled','cancelled') NOT NULL DEFAULT 'pending',
  `pr_id` int unsigned DEFAULT NULL,
  `transfer_id` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ia_indent_item` (`indent_item_id`),
  KEY `idx_ia_type` (`allocation_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 9. PURCHASE REQUISITIONS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `purchase_requisitions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `pr_no` varchar(50) NOT NULL,
  `indent_id` int unsigned DEFAULT NULL,
  `requested_by` int unsigned DEFAULT NULL,
  `department_id` int unsigned DEFAULT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `warehouse_id` int unsigned DEFAULT NULL,
  `priority` enum('low','medium','high','urgent') NOT NULL DEFAULT 'medium',
  `status` enum('draft','pending_approval','approved','partially_ordered','fully_ordered','rejected','cancelled') NOT NULL DEFAULT 'draft',
  `approved_by` int unsigned DEFAULT NULL,
  `approved_at` timestamp NULL DEFAULT NULL,
  `notes` text,
  `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_pr_no` (`pr_no`, `company_id`),
  KEY `idx_pr_indent` (`indent_id`),
  KEY `idx_pr_status` (`status`),
  KEY `idx_pr_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 10. PURCHASE REQUISITION ITEMS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `purchase_requisition_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `pr_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `required_qty` decimal(14,4) NOT NULL,
  `ordered_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `estimated_rate` decimal(14,4) DEFAULT NULL,
  `supplier_id` int unsigned DEFAULT NULL,
  `required_date` date DEFAULT NULL,
  `status` enum('pending','ordered','cancelled') NOT NULL DEFAULT 'pending',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_pri_pr` (`pr_id`),
  KEY `idx_pri_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 11. PURCHASE ORDERS (procurement from vendors)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `procurement_orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `po_no` varchar(50) NOT NULL,
  `pr_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned NOT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `warehouse_id` int unsigned DEFAULT NULL,
  `order_date` date NOT NULL,
  `expected_delivery` date DEFAULT NULL,
  `payment_term_id` int unsigned DEFAULT NULL,
  `currency_id` int unsigned DEFAULT NULL,
  `exchange_rate` decimal(14,6) DEFAULT 1.000000,
  `total_amount` decimal(16,4) DEFAULT 0,
  `tax_amount` decimal(16,4) DEFAULT 0,
  `status` enum('draft','submitted','confirmed','partially_received','fully_received','cancelled') NOT NULL DEFAULT 'draft',
  `supplier_confirmation` enum('pending','accepted','rejected') NOT NULL DEFAULT 'pending',
  `notes` text,
  `created_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_po_no` (`po_no`, `company_id`),
  KEY `idx_po_supplier` (`supplier_id`),
  KEY `idx_po_pr` (`pr_id`),
  KEY `idx_po_status` (`status`),
  KEY `idx_po_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 12. PURCHASE ORDER ITEMS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `procurement_order_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `po_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `ordered_qty` decimal(14,4) NOT NULL,
  `received_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `rate` decimal(14,4) NOT NULL,
  `amount` decimal(16,4) DEFAULT NULL,
  `lot_no` varchar(100) DEFAULT NULL,
  `expected_date` date DEFAULT NULL,
  `status` enum('pending','partially_received','fully_received','cancelled') NOT NULL DEFAULT 'pending',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_poi_po` (`po_id`),
  KEY `idx_poi_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 13. GOODS RECEIPT NOTES (GRN)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `grn` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `grn_no` varchar(50) NOT NULL,
  `po_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned DEFAULT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `received_by` int unsigned DEFAULT NULL,
  `received_date` date NOT NULL,
  `invoice_no` varchar(100) DEFAULT NULL,
  `invoice_date` date DEFAULT NULL,
  `vehicle_no` varchar(100) DEFAULT NULL,
  `challan_no` varchar(100) DEFAULT NULL,
  `total_qty` decimal(14,4) DEFAULT 0,
  `qc_status` enum('pending','passed','partial','failed') NOT NULL DEFAULT 'pending',
  `status` enum('draft','confirmed','qc_pending','qc_passed','qc_failed','stocked','cancelled') NOT NULL DEFAULT 'draft',
  `notes` text,
  `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_grn_no` (`grn_no`, `company_id`),
  KEY `idx_grn_po` (`po_id`),
  KEY `idx_grn_supplier` (`supplier_id`),
  KEY `idx_grn_warehouse` (`warehouse_id`),
  KEY `idx_grn_status` (`status`),
  KEY `idx_grn_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 14. GRN ITEMS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `grn_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `po_item_id` int unsigned DEFAULT 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 NOT NULL,
  `received_qty` decimal(14,4) NOT NULL,
  `accepted_qty` decimal(14,4) DEFAULT NULL,
  `rejected_qty` decimal(14,4) DEFAULT 0,
  `location_id` int unsigned DEFAULT NULL,
  `qc_status` enum('pending','passed','failed') NOT NULL DEFAULT 'pending',
  `expiry_date` date DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_gi_grn` (`grn_id`),
  KEY `idx_gi_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 15. STOCK TRANSERS (inter-warehouse)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `stock_transfers` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `transfer_no` varchar(50) NOT NULL,
  `from_warehouse_id` int unsigned NOT NULL,
  `to_warehouse_id` int unsigned NOT NULL,
  `indent_id` int unsigned DEFAULT NULL,
  `requested_by` int unsigned DEFAULT NULL,
  `approved_by` int unsigned DEFAULT NULL,
  `status` enum('draft','pending_approval','approved','in_transit','received','cancelled') NOT NULL DEFAULT 'draft',
  `notes` text,
  `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_transfer_no` (`transfer_no`, `company_id`),
  KEY `idx_st_status` (`status`),
  KEY `idx_st_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 16. STOCK TRANSFER ITEMS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `stock_transfer_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `transfer_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,
  `uom_id` int unsigned NOT NULL,
  `requested_qty` decimal(14,4) NOT NULL,
  `sent_qty` decimal(14,4) DEFAULT 0,
  `received_qty` decimal(14,4) DEFAULT 0,
  `stock_id` int unsigned DEFAULT NULL,
  `status` enum('pending','sent','received','cancelled') NOT NULL DEFAULT 'pending',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_sti_transfer` (`transfer_id`),
  KEY `idx_sti_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- Seed: Default warehouses per factory
-- -----------------------------------------------------------
INSERT IGNORE INTO `warehouses` (`company_id`, `factory_id`, `name`, `code`, `is_default`, `status`)
SELECT 1, f.id, CONCAT(f.name, ' Main Warehouse'), CONCAT(f.code, '-WH-MAIN'), 1, 'active'
FROM `master_factories` f
WHERE f.status = 'active'
AND NOT EXISTS (SELECT 1 FROM `warehouses` w WHERE w.factory_id = f.id AND w.company_id = 1);


-- ============================================================
-- FILE: migration_procurement_phase2.sql
-- ============================================================

-- ============================================================
-- FashCognitive - Procurement Module Phase 2
-- Missing Tables: Adjustments, Returns, RFQ, Quotations,
-- ASN, Supplier Invoices, PO Revisions, Approvals, QC
-- ============================================================

-- -----------------------------------------------------------
-- 17. STOCK ADJUSTMENTS (formal adjustment workflow)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `stock_adjustments` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `adjustment_no` varchar(50) NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `adjustment_type` enum('shortage','surplus','damage','expiry','reclassification','opening') NOT NULL DEFAULT 'shortage',
  `reason` text,
  `requested_by` int unsigned DEFAULT NULL,
  `approved_by` int unsigned DEFAULT NULL,
  `status` enum('draft','pending_approval','approved','rejected','posted') NOT NULL DEFAULT 'draft',
  `posted_at` timestamp NULL DEFAULT NULL,
  `notes` text,
  `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_sa_no` (`adjustment_no`, `company_id`),
  KEY `idx_sa_warehouse` (`warehouse_id`),
  KEY `idx_sa_status` (`status`),
  KEY `idx_sa_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `stock_adjustment_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `adjustment_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 NOT NULL,
  `stock_id` int unsigned DEFAULT NULL,
  `system_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `physical_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `adjustment_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `unit_cost` decimal(14,4) DEFAULT NULL,
  `reason` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_sai_adj` (`adjustment_id`),
  KEY `idx_sai_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 18. MATERIAL RETURNS (production → warehouse)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `material_returns` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `return_no` varchar(50) NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `indent_id` int unsigned DEFAULT NULL,
  `issue_reference` varchar(100) DEFAULT NULL,
  `returned_by` int unsigned DEFAULT NULL,
  `return_date` date NOT NULL,
  `status` enum('draft','confirmed','cancelled') NOT NULL DEFAULT 'draft',
  `notes` text,
  `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_mr_no` (`return_no`, `company_id`),
  KEY `idx_mr_warehouse` (`warehouse_id`),
  KEY `idx_mr_status` (`status`),
  KEY `idx_mr_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `material_return_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `return_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 NOT NULL,
  `issued_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `used_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `returned_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `condition` enum('good','damaged','expired') NOT NULL DEFAULT 'good',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_mri_return` (`return_id`),
  KEY `idx_mri_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 19. MATERIAL ISSUES (warehouse → production)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `material_issues` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `issue_no` varchar(50) NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `indent_id` int unsigned DEFAULT NULL,
  `production_order` varchar(100) DEFAULT NULL,
  `style_no` varchar(100) DEFAULT NULL,
  `color` varchar(100) DEFAULT NULL,
  `issued_to` int unsigned DEFAULT NULL,
  `issue_date` date NOT NULL,
  `status` enum('draft','issued','cancelled') NOT NULL DEFAULT 'draft',
  `notes` text,
  `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_mi_no` (`issue_no`, `company_id`),
  KEY `idx_mi_warehouse` (`warehouse_id`),
  KEY `idx_mi_status` (`status`),
  KEY `idx_mi_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `material_issue_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `issue_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 NOT NULL,
  `stock_id` int unsigned DEFAULT NULL,
  `requested_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `issued_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `unit_cost` decimal(14,4) DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_mii_issue` (`issue_id`),
  KEY `idx_mii_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 20. PURCHASE RFQ (Request for Quotation)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `purchase_rfq` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `rfq_no` varchar(50) NOT NULL,
  `pr_id` int unsigned DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `description` text,
  `required_date` date DEFAULT NULL,
  `closing_date` date DEFAULT NULL,
  `created_by` int unsigned DEFAULT NULL,
  `status` enum('draft','sent','partial_responses','closed','cancelled') NOT NULL DEFAULT 'draft',
  `notes` text,
  `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_rfq_no` (`rfq_no`, `company_id`),
  KEY `idx_rfq_pr` (`pr_id`),
  KEY `idx_rfq_status` (`status`),
  KEY `idx_rfq_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `purchase_rfq_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `rfq_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `required_qty` decimal(14,4) NOT NULL,
  `specifications` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_rfi_rfq` (`rfq_id`),
  KEY `idx_rfi_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `purchase_rfq_suppliers` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `rfq_id` int unsigned NOT NULL,
  `supplier_id` int unsigned NOT NULL,
  `status` enum('invited','responded','declined') NOT NULL DEFAULT 'invited',
  `responded_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_rfs_rfq` (`rfq_id`),
  KEY `idx_rfs_supplier` (`supplier_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 21. SUPPLIER QUOTATIONS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `supplier_quotations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `rfq_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned NOT NULL,
  `quotation_no` varchar(100) DEFAULT NULL,
  `quotation_date` date NOT NULL,
  `valid_until` date DEFAULT NULL,
  `payment_terms` varchar(255) DEFAULT NULL,
  `delivery_days` int unsigned DEFAULT NULL,
  `moq` varchar(255) DEFAULT NULL,
  `currency_id` int unsigned DEFAULT NULL,
  `total_amount` decimal(16,4) DEFAULT 0,
  `notes` text,
  `status` enum('draft','submitted','shortlisted','accepted','rejected') NOT NULL DEFAULT 'draft',
  `ai_score` decimal(5,2) 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`),
  KEY `idx_sq_rfq` (`rfq_id`),
  KEY `idx_sq_supplier` (`supplier_id`),
  KEY `idx_sq_status` (`status`),
  KEY `idx_sq_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `supplier_quotation_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `quotation_id` int unsigned NOT NULL,
  `rfq_item_id` int unsigned DEFAULT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `qty` decimal(14,4) NOT NULL,
  `unit_price` decimal(14,4) NOT NULL,
  `total_price` decimal(16,4) DEFAULT NULL,
  `lead_time_days` int unsigned DEFAULT NULL,
  `moq` int unsigned DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_sqi_quotation` (`quotation_id`),
  KEY `idx_sqi_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 22. ADVANCE SHIPPING NOTICES (ASN)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `asn` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `asn_no` varchar(50) NOT NULL,
  `po_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `ship_date` date DEFAULT NULL,
  `eta_date` date DEFAULT NULL,
  `actual_arrival` date DEFAULT NULL,
  `vehicle_no` varchar(100) DEFAULT NULL,
  `challan_no` varchar(100) DEFAULT NULL,
  `invoice_no` varchar(100) DEFAULT NULL,
  `total_boxes` int unsigned DEFAULT NULL,
  `total_rolls` int unsigned DEFAULT NULL,
  `total_qty` decimal(14,4) DEFAULT 0,
  `status` enum('draft','in_transit','arrived','under_inspection','received','rejected') NOT NULL DEFAULT 'draft',
  `notes` text,
  `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_asn_no` (`asn_no`, `company_id`),
  KEY `idx_asn_po` (`po_id`),
  KEY `idx_asn_supplier` (`supplier_id`),
  KEY `idx_asn_status` (`status`),
  KEY `idx_asn_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `asn_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `asn_id` int unsigned NOT NULL,
  `po_item_id` int unsigned DEFAULT 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 NOT NULL,
  `shipped_qty` decimal(14,4) NOT NULL,
  `received_qty` decimal(14,4) DEFAULT NULL,
  `boxes` int unsigned DEFAULT NULL,
  `rolls` int unsigned DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ai_asn` (`asn_id`),
  KEY `idx_ai_item` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 23. SUPPLIER INVOICES
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `supplier_invoices` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `invoice_no` varchar(100) NOT NULL,
  `po_id` int unsigned DEFAULT NULL,
  `grn_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned NOT NULL,
  `invoice_date` date NOT NULL,
  `invoice_amount` decimal(16,4) NOT NULL,
  `tax_amount` decimal(16,4) DEFAULT 0,
  `total_amount` decimal(16,4) DEFAULT 0,
  `currency_id` int unsigned DEFAULT NULL,
  `exchange_rate` decimal(14,6) DEFAULT 1.000000,
  `payment_status` enum('pending','partial','paid','overdue') NOT NULL DEFAULT 'pending',
  `paid_amount` decimal(16,4) DEFAULT 0,
  `paid_date` date DEFAULT NULL,
  `due_date` date DEFAULT NULL,
  `matching_status` enum('pending','matched','mismatch','exception') NOT NULL DEFAULT 'pending',
  `notes` text,
  `status` enum('draft','submitted','verified','approved','paid','cancelled') NOT NULL DEFAULT 'draft',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_si_po` (`po_id`),
  KEY `idx_si_supplier` (`supplier_id`),
  KEY `idx_si_status` (`status`),
  KEY `idx_si_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 24. PO REVISIONS (amendment history)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `po_revisions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `po_id` int unsigned NOT NULL,
  `revision_no` int unsigned NOT NULL DEFAULT 1,
  `revision_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `revision_by` int unsigned DEFAULT NULL,
  `reason` text,
  `changes_json` longtext,
  `status` enum('draft','superseded') NOT NULL DEFAULT 'draft',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_por_po` (`po_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 25. MATERIAL INDENT APPROVALS (audit trail)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `material_indent_approvals` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `indent_id` int unsigned NOT NULL,
  `approver_id` int unsigned NOT NULL,
  `action` enum('submitted','approved','rejected','revision_requested') NOT NULL,
  `remarks` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_mia_indent` (`indent_id`),
  KEY `idx_mia_approver` (`approver_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 26. SUPPLIER PORTAL USERS
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `supplier_portal_users` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `supplier_id` int unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password_hash` varchar(255) NOT NULL,
  `phone` varchar(50) DEFAULT NULL,
  `role` enum('admin','viewer') NOT NULL DEFAULT 'admin',
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `last_login` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_spu_email` (`email`),
  KEY `idx_spu_supplier` (`supplier_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- Add expected_delivery to indent_allocations if missing
-- -----------------------------------------------------------
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'indent_allocations' AND COLUMN_NAME = 'expected_delivery');
SET @sql = IF(@col_exists = 0,
  'ALTER TABLE `indent_allocations` ADD COLUMN `expected_delivery` date DEFAULT NULL AFTER `status`',
  'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


-- ============================================================
-- FILE: migration_procurement_v2.sql
-- ============================================================

-- ============================================================
-- FashCognitive Intelligent Procurement — Missing Tables
-- ============================================================

-- 1. Warehouse Reservations (reserve stock before procurement)
CREATE TABLE IF NOT EXISTS `warehouse_reservations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `reservation_no` varchar(50) NOT NULL,
  `indent_id` int unsigned DEFAULT NULL,
  `indent_item_id` int unsigned DEFAULT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `required_qty` decimal(14,4) NOT NULL,
  `reserved_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `fulfilled_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `status` enum('active','partially_fulfilled','fulfilled','cancelled') NOT NULL DEFAULT 'active',
  `reserved_by` int unsigned DEFAULT NULL,
  `notes` text,
  `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 `reservation_no` (`reservation_no`),
  KEY `indent` (`indent_id`),
  KEY `warehouse` (`warehouse_id`,`item_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 2. Quotation Comparisons (AI scoring records)
CREATE TABLE IF NOT EXISTS `quotation_comparisons` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `rfq_id` int unsigned NOT NULL,
  `comparison_date` date NOT NULL,
  `total_quotations` int unsigned NOT NULL DEFAULT 0,
  `recommended_quotation_id` int unsigned DEFAULT NULL,
  `recommendation_reason` text,
  `comparison_data` json DEFAULT NULL,
  `created_by` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `rfq` (`rfq_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 3. Vendor Scorecards (performance tracking)
CREATE TABLE IF NOT EXISTS `vendor_scorecards` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `supplier_id` int unsigned NOT NULL,
  `period_start` date NOT NULL,
  `period_end` date NOT NULL,
  `total_orders` int unsigned NOT NULL DEFAULT 0,
  `on_time_deliveries` int unsigned NOT NULL DEFAULT 0,
  `quality_pass_rate` decimal(5,2) NOT NULL DEFAULT 0,
  `avg_lead_time_days` decimal(6,1) NOT NULL DEFAULT 0,
  `price_competitiveness` decimal(5,2) NOT NULL DEFAULT 0,
  `response_rate` decimal(5,2) NOT NULL DEFAULT 0,
  `overall_score` decimal(5,2) NOT NULL DEFAULT 0,
  `rating` enum('A','B','C','D','F') DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `supplier` (`supplier_id`),
  KEY `period` (`period_start`,`period_end`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 4. Vendor Price History (track price trends)
CREATE TABLE IF NOT EXISTS `vendor_price_history` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `supplier_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `unit_price` decimal(14,4) NOT NULL,
  `currency_code` varchar(10) DEFAULT 'INR',
  `quotation_id` int unsigned DEFAULT NULL,
  `po_id` int unsigned DEFAULT NULL,
  `recorded_date` date NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `supplier_item` (`supplier_id`,`item_id`),
  KEY `date` (`recorded_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 5. Procurement Approvals (multi-level)
CREATE TABLE IF NOT EXISTS `procurement_approvals` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `entity_type` varchar(50) NOT NULL COMMENT 'indent, pr, po, invoice',
  `entity_id` int unsigned NOT NULL,
  `approval_level` int unsigned NOT NULL DEFAULT 1,
  `approver_id` int unsigned DEFAULT NULL,
  `approver_name` varchar(255) DEFAULT NULL,
  `status` enum('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `remarks` text,
  `decided_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `entity` (`entity_type`,`entity_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 6. Procurement Audit Logs
CREATE TABLE IF NOT EXISTS `procurement_audit_logs` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `entity_type` varchar(50) NOT NULL,
  `entity_id` int unsigned NOT NULL,
  `action` varchar(50) NOT NULL,
  `user_id` int unsigned DEFAULT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `old_value` text,
  `new_value` text,
  `ip_address` varchar(45) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `entity` (`entity_type`,`entity_id`),
  KEY `created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 7. Purchase Returns
CREATE TABLE IF NOT EXISTS `purchase_returns` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `return_no` varchar(50) NOT NULL,
  `po_id` int unsigned DEFAULT NULL,
  `grn_id` int unsigned DEFAULT NULL,
  `supplier_id` int unsigned NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `return_date` date NOT NULL,
  `reason` enum('quality','damage','excess','wrong_item','other') NOT NULL DEFAULT 'quality',
  `total_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `total_value` decimal(16,4) NOT NULL DEFAULT 0,
  `status` enum('draft','approved','shipped','received_by_supplier','cancelled') NOT NULL DEFAULT 'draft',
  `notes` text,
  `created_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 `return_no` (`return_no`),
  KEY `po` (`po_id`),
  KEY `supplier` (`supplier_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 8. Purchase Return Items
CREATE TABLE IF NOT EXISTS `purchase_return_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `return_id` int unsigned NOT NULL,
  `po_item_id` int unsigned DEFAULT NULL,
  `grn_item_id` int unsigned DEFAULT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `return_qty` decimal(14,4) NOT NULL,
  `unit_rate` decimal(14,4) NOT NULL DEFAULT 0,
  `reason` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `return` (`return_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: migration_po_sap_style.sql
-- ============================================================

-- ============================================================
-- SAP-Style Purchase Order Enhancement Migration
-- ============================================================

-- 1. Enhance procurement_orders with SAP-style header fields
ALTER TABLE procurement_orders
  ADD COLUMN document_type ENUM('standard','service','stock_transfer','blanket') DEFAULT 'standard' AFTER po_no,
  ADD COLUMN purchasing_org VARCHAR(100) NULL AFTER document_type,
  ADD COLUMN purchasing_group VARCHAR(100) NULL AFTER purchasing_org,
  ADD COLUMN incoterms VARCHAR(50) NULL AFTER purchasing_group,
  ADD COLUMN delivery_terms TEXT NULL AFTER incoterms,
  ADD COLUMN currency_code VARCHAR(10) DEFAULT 'INR' AFTER delivery_terms,
  ADD COLUMN freight_amount DECIMAL(16,4) DEFAULT 0 AFTER currency_code,
  ADD COLUMN insurance_amount DECIMAL(16,4) DEFAULT 0 AFTER freight_amount,
  ADD COLUMN discount_amount DECIMAL(16,4) DEFAULT 0 AFTER insurance_amount,
  ADD COLUMN subtotal DECIMAL(16,4) DEFAULT 0 AFTER discount_amount,
  ADD COLUMN tax_rate DECIMAL(8,4) DEFAULT 18.0000 AFTER subtotal,
  ADD COLUMN grand_total DECIMAL(16,4) DEFAULT 0 AFTER tax_rate,
  ADD COLUMN approval_level INT DEFAULT 0 AFTER grand_total,
  ADD COLUMN sent_to_supplier_at TIMESTAMP NULL AFTER approval_level,
  ADD COLUMN payment_status ENUM('unpaid','partial','paid','overdue') DEFAULT 'unpaid' AFTER sent_to_supplier_at,
  ADD COLUMN payment_completed_at TIMESTAMP NULL AFTER payment_status,
  ADD COLUMN closed_at TIMESTAMP NULL AFTER payment_completed_at,
  ADD COLUMN revised_at TIMESTAMP NULL AFTER closed_at,
  ADD COLUMN revision_no INT DEFAULT 0 AFTER revised_at;

-- 2. Enhance procurement_order_items with line numbers + detail fields
ALTER TABLE procurement_order_items
  ADD COLUMN line_no INT NOT NULL DEFAULT 10 AFTER po_id,
  ADD COLUMN vendor_material_code VARCHAR(100) NULL AFTER item_id,
  ADD COLUMN material_description VARCHAR(255) NULL AFTER vendor_material_code,
  ADD COLUMN tax_code VARCHAR(20) NULL AFTER notes,
  ADD COLUMN discount_pct DECIMAL(8,4) DEFAULT 0 AFTER tax_code,
  ADD COLUMN discount_amount DECIMAL(16,4) DEFAULT 0 AFTER discount_pct,
  ADD COLUMN freight_per_unit DECIMAL(14,4) DEFAULT 0 AFTER discount_amount,
  ADD COLUMN qc_required TINYINT(1) DEFAULT 1 AFTER freight_per_unit,
  ADD COLUMN gr_required TINYINT(1) DEFAULT 1 AFTER qc_required,
  ADD COLUMN invoice_verification_required TINYINT(1) DEFAULT 1 AFTER gr_required,
  ADD COLUMN batch_required TINYINT(1) DEFAULT 0 AFTER invoice_verification_required,
  ADD COLUMN delivery_date DATE NULL AFTER expected_date,
  ADD COLUMN plant_id INT UNSIGNED NULL AFTER delivery_date;

-- 3. Delivery Schedules table (staggered deliveries per PO item)
CREATE TABLE IF NOT EXISTS po_delivery_schedules (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  po_id INT UNSIGNED NOT NULL,
  po_item_id INT UNSIGNED NOT NULL,
  delivery_no INT NOT NULL DEFAULT 1,
  delivery_date DATE NOT NULL,
  quantity DECIMAL(14,4) NOT NULL,
  received_qty DECIMAL(14,4) DEFAULT 0,
  status ENUM('pending','partially_received','fully_received','cancelled') DEFAULT 'pending',
  notes TEXT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_po_id (po_id),
  KEY idx_po_item_id (po_item_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 4. Approval Workflow table
CREATE TABLE IF NOT EXISTS po_approvals (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  po_id INT UNSIGNED NOT NULL,
  approval_level INT NOT NULL,
  role_name VARCHAR(100) NOT NULL,
  user_id INT UNSIGNED NULL,
  status ENUM('pending','approved','rejected','skipped') DEFAULT 'pending',
  comments TEXT NULL,
  approved_at TIMESTAMP NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  KEY idx_po_id (po_id),
  KEY idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 5. Attachments table
CREATE TABLE IF NOT EXISTS po_attachments (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  po_id INT UNSIGNED NOT NULL,
  file_name VARCHAR(255) NOT NULL,
  file_path VARCHAR(500) NOT NULL,
  file_type VARCHAR(100) NULL,
  file_size INT UNSIGNED NULL,
  category ENUM('quotation','tech_pack','bom','specification','agreement','other') DEFAULT 'other',
  uploaded_by INT UNSIGNED NULL,
  uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  KEY idx_po_id (po_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 6. AI Insights cache table
CREATE TABLE IF NOT EXISTS po_ai_insights (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  po_id INT UNSIGNED NOT NULL,
  supplier_score DECIMAL(5,2) NULL,
  previous_price DECIMAL(14,4) NULL,
  price_change_pct DECIMAL(8,4) NULL,
  lead_time_days INT NULL,
  on_time_delivery_pct DECIMAL(5,2) NULL,
  quality_acceptance_pct DECIMAL(5,2) NULL,
  alternative_supplier_id INT UNSIGNED NULL,
  alternative_price DECIMAL(14,4) NULL,
  estimated_savings DECIMAL(16,4) NULL,
  recommendation TEXT NULL,
  duplicate_po_alert TINYINT(1) DEFAULT 0,
  excess_stock_alert TINYINT(1) DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  KEY idx_po_id (po_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 7. Update PO statuses to full SAP-style workflow
ALTER TABLE procurement_orders
  MODIFY COLUMN status ENUM(
    'draft','pending_approval','approved','sent_to_supplier',
    'partially_received','fully_received',
    'invoice_received','payment_completed','closed',
    'cancelled'
  ) DEFAULT 'draft';

-- 8. Update PR statuses
ALTER TABLE purchase_requisitions
  MODIFY COLUMN status ENUM(
    'draft','pending_approval','approved','partially_ordered','fully_ordered',
    'rejected','cancelled'
  ) DEFAULT 'draft';


-- ============================================================
-- FILE: migration_po_from_pr.sql
-- ============================================================

-- Add PR traceability columns to procurement_order_items
-- This allows tracking which Purchase Requisition item each PO item came from

ALTER TABLE procurement_order_items
  ADD COLUMN pr_id INT UNSIGNED NULL AFTER po_id,
  ADD COLUMN pr_item_id INT UNSIGNED NULL AFTER pr_id,
  ADD INDEX idx_pr_id (pr_id),
  ADD INDEX idx_pr_item_id (pr_item_id);


-- ============================================================
-- FILE: migration_po_from_quotation.sql
-- ============================================================

-- Add RFQ/Quotation traceability to procurement_orders
ALTER TABLE procurement_orders
  ADD COLUMN rfq_id INT UNSIGNED NULL AFTER pr_id,
  ADD COLUMN quotation_id INT UNSIGNED NULL AFTER rfq_id,
  ADD INDEX idx_po_rfq (rfq_id),
  ADD INDEX idx_po_quotation (quotation_id);

-- Add RFQ/Quotation traceability to procurement_order_items
ALTER TABLE procurement_order_items
  ADD COLUMN rfq_item_id INT UNSIGNED NULL AFTER pr_item_id,
  ADD COLUMN quotation_item_id INT UNSIGNED NULL AFTER rfq_item_id;


-- ============================================================
-- FILE: migration_share_tokens.sql
-- ============================================================

-- -----------------------------------------------------------
-- Share Tokens Table (encrypted document share links)
-- -----------------------------------------------------------
CREATE TABLE `share_tokens` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `token` varchar(128) NOT NULL,
  `entity_type` varchar(50) NOT NULL DEFAULT 'style',
  `entity_id` int unsigned NOT NULL,
  `created_by` int unsigned DEFAULT NULL,
  `expires_at` timestamp NULL DEFAULT NULL,
  `access_count` int unsigned NOT NULL DEFAULT 0,
  `max_access` int unsigned DEFAULT NULL,
  `is_active` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `token` (`token`),
  KEY `entity` (`entity_type`, `entity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: migration_rfq_sap_enhancements.sql
-- ============================================================

-- ============================================================
-- SAP MM-Style RFQ Enhancement Migration
-- ============================================================

-- 1. Enhance purchase_rfq with SAP-style fields
ALTER TABLE purchase_rfq
  ADD COLUMN document_type ENUM('standard','blanket','framework','urgent') DEFAULT 'standard' AFTER pr_id,
  ADD COLUMN currency_code VARCHAR(10) DEFAULT 'INR' AFTER document_type,
  ADD COLUMN incoterm_id INT UNSIGNED NULL AFTER currency_code,
  ADD COLUMN incoterm_name VARCHAR(50) NULL AFTER incoterm_id,
  ADD COLUMN priority ENUM('low','medium','high','urgent') DEFAULT 'medium' AFTER incoterm_name,
  ADD COLUMN approval_status ENUM('none','pending','approved','rejected') DEFAULT 'none' AFTER priority,
  ADD COLUMN approved_by INT UNSIGNED NULL AFTER approval_status,
  ADD COLUMN approved_at TIMESTAMP NULL AFTER approved_by,
  ADD COLUMN sent_at TIMESTAMP NULL AFTER approved_at,
  ADD COLUMN total_amount DECIMAL(16,4) DEFAULT 0 AFTER sent_at,
  ADD COLUMN currency_symbol VARCHAR(5) DEFAULT '₹' AFTER total_amount;

-- 2. RFQ Attachments table
CREATE TABLE IF NOT EXISTS rfq_attachments (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  rfq_id INT UNSIGNED NOT NULL,
  file_name VARCHAR(255) NOT NULL,
  file_path VARCHAR(500) NOT NULL,
  file_type VARCHAR(100) NULL,
  file_size INT UNSIGNED NULL,
  category ENUM('specification','tech_pack','bom','quotation','drawing','image','test_report','other') DEFAULT 'other',
  uploaded_by INT UNSIGNED NULL,
  uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  KEY idx_rfa_rfq (rfq_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 3. RFQ Approvals table (multi-level)
CREATE TABLE IF NOT EXISTS rfq_approvals (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  rfq_id INT UNSIGNED NOT NULL,
  approval_level INT UNSIGNED NOT NULL,
  role_name VARCHAR(100) NOT NULL,
  user_id INT UNSIGNED NULL,
  status ENUM('pending','approved','rejected','skipped') DEFAULT 'pending',
  comments TEXT NULL,
  decided_at TIMESTAMP NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  KEY idx_rfa_rfq (rfq_id),
  KEY idx_rfa_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 4. RFQ Audit Logs (for timeline)
CREATE TABLE IF NOT EXISTS rfq_audit_logs (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  rfq_id INT UNSIGNED NOT NULL,
  action VARCHAR(50) NOT NULL,
  description TEXT NULL,
  user_id INT UNSIGNED NULL,
  user_name VARCHAR(255) NULL,
  old_value TEXT NULL,
  new_value TEXT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  KEY idx_rfal_rfq (rfq_id),
  KEY idx_rfal_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 5. Update RFQ status to include approval states
ALTER TABLE purchase_rfq
  MODIFY COLUMN status ENUM('draft','pending_approval','approved','sent','partial_responses','closed','cancelled') NOT NULL DEFAULT 'draft';


-- ============================================================
-- FILE: migration_vendor_portal_tokens.sql
-- ============================================================

-- Vendor Portal Tokens: Allow suppliers to respond to RFQs via a public link
CREATE TABLE IF NOT EXISTS vendor_portal_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  company_id INT NOT NULL,
  rfq_id INT NOT NULL,
  supplier_id INT NOT NULL,
  token VARCHAR(64) NOT NULL UNIQUE,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  expires_at DATETIME DEFAULT NULL,
  access_count INT NOT NULL DEFAULT 0,
  max_access INT NOT NULL DEFAULT 50,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_rfq_supplier (rfq_id, supplier_id),
  KEY idx_token (token),
  KEY idx_company (company_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Auto-generate tokens when RFQ is sent (trigger via API)


-- ============================================================
-- FILE: migration_manufacturing.sql
-- ============================================================

-- ============================================================
-- FashCognitive Manufacturing Execution Module
-- Production Orders (Discrete) + Process Orders (Batch)
-- ============================================================

-- ============================================================
-- 1. Production Lines (Master)
-- ============================================================
CREATE TABLE IF NOT EXISTS `master_production_lines` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `factory_id` int unsigned DEFAULT NULL,
  `line_name` varchar(100) NOT NULL,
  `line_code` varchar(20) DEFAULT NULL,
  `capacity_per_day` int unsigned DEFAULT NULL COMMENT 'Units per day',
  `section` enum('cutting','sewing','finishing','packing','printing','embroidery','washing','dyeing','knitting','other') DEFAULT 'sewing',
  `status` enum('active','inactive','maintenance') NOT NULL DEFAULT 'active',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `factory_id` (`factory_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 2. Work Centers (Machines / Tables)
-- ============================================================
CREATE TABLE IF NOT EXISTS `master_work_centers` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `factory_id` int unsigned DEFAULT NULL,
  `line_id` int unsigned DEFAULT NULL,
  `work_center_name` varchar(150) NOT NULL,
  `work_center_code` varchar(30) DEFAULT NULL,
  `machine_type` varchar(100) DEFAULT NULL COMMENT 'Overlock, Flatlock, Single Needle, Jet Dyeing, etc.',
  `category` enum('sewing','cutting','finishing','packing','printing','embroidery','dyeing','washing','knitting','compacting','other') DEFAULT 'sewing',
  `hourly_rate` decimal(10,2) DEFAULT 0,
  `capacity_per_hour` decimal(8,2) DEFAULT NULL,
  `status` enum('available','in_use','maintenance','idle') NOT NULL DEFAULT 'available',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `factory_id` (`factory_id`),
  KEY `line_id` (`line_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 3. Production Orders (Discrete Manufacturing)
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_no` varchar(30) NOT NULL,
  `order_type` enum('production','subcontract','rework','sample','maintenance') NOT NULL DEFAULT 'production',
  `buyer_po_id` int unsigned DEFAULT NULL COMMENT 'master_buyer_pos.id',
  `style_id` int unsigned DEFAULT NULL COMMENT 'master_styles.id',
  `color` varchar(50) DEFAULT NULL,
  `size` varchar(20) DEFAULT NULL,
  `description` text,
  `planned_qty` int unsigned NOT NULL DEFAULT 0,
  `completed_qty` int unsigned NOT NULL DEFAULT 0,
  `rejected_qty` int unsigned NOT NULL DEFAULT 0,
  `scrapped_qty` int unsigned NOT NULL DEFAULT 0,
  `uom` varchar(20) DEFAULT 'PCS',
  `factory_id` int unsigned DEFAULT NULL,
  `line_id` int unsigned DEFAULT NULL,
  `work_center_id` int unsigned DEFAULT NULL,
  `planned_start_date` date DEFAULT NULL,
  `planned_end_date` date DEFAULT NULL,
  `actual_start_date` date DEFAULT NULL,
  `actual_end_date` date DEFAULT NULL,
  `priority` enum('low','medium','high','urgent') NOT NULL DEFAULT 'medium',
  `status` enum('draft','planned','released','in_progress','paused','completed','closed','cancelled') NOT NULL DEFAULT 'draft',
  `completion_pct` decimal(5,2) NOT NULL DEFAULT 0,
  `total_smv` decimal(10,2) DEFAULT NULL,
  `total_sam` decimal(10,2) DEFAULT NULL,
  `estimated_cost` decimal(12,2) DEFAULT 0,
  `actual_cost` decimal(12,2) DEFAULT 0,
  `notes` text,
  `created_by` int unsigned DEFAULT NULL,
  `approved_by` int unsigned DEFAULT NULL,
  `approved_at` datetime DEFAULT NULL,
  `released_at` datetime 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 `prod_order_no` (`prod_order_no`, `company_id`),
  KEY `company_id` (`company_id`),
  KEY `buyer_po_id` (`buyer_po_id`),
  KEY `style_id` (`style_id`),
  KEY `factory_id` (`factory_id`),
  KEY `line_id` (`line_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 4. Production Order Operations (Routing Steps)
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_operations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `sequence` int unsigned NOT NULL DEFAULT 10,
  `operation_name` varchar(150) NOT NULL,
  `operation_type` enum('cutting','bundling','printing','embroidery','sewing','finishing','packing','quality','other') DEFAULT 'sewing',
  `work_center_id` int unsigned DEFAULT NULL,
  `machine_type` varchar(100) DEFAULT NULL,
  `planned_qty` int unsigned NOT NULL DEFAULT 0,
  `completed_qty` int unsigned NOT NULL DEFAULT 0,
  `rejected_qty` int unsigned NOT NULL DEFAULT 0,
  `operators_required` int unsigned DEFAULT 1,
  `smv` decimal(8,2) DEFAULT 0,
  `sam` decimal(8,2) DEFAULT NULL,
  `planned_hours` decimal(6,2) DEFAULT NULL,
  `actual_hours` decimal(6,2) DEFAULT NULL,
  `planned_start_date` date DEFAULT NULL,
  `planned_end_date` date DEFAULT NULL,
  `actual_start_date` date DEFAULT NULL,
  `actual_end_date` date DEFAULT NULL,
  `status` enum('pending','in_progress','completed','on_hold','skipped') NOT NULL DEFAULT 'pending',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `work_center_id` (`work_center_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 5. Production Order Materials (BOM per Order)
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_materials` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `item_id` int unsigned DEFAULT NULL COMMENT 'master_items.id',
  `material_name` varchar(255) NOT NULL,
  `material_type` enum('fabric','trim','accessory','packaging','chemical','other') DEFAULT 'fabric',
  `color` varchar(50) DEFAULT NULL,
  `size` varchar(20) DEFAULT NULL,
  `uom` varchar(20) DEFAULT 'Kg',
  `required_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `issued_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `consumed_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `returned_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `wastage_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `rate` decimal(12,2) DEFAULT 0,
  `total_cost` decimal(12,2) DEFAULT 0,
  `warehouse_id` int unsigned DEFAULT NULL,
  `batch_no` varchar(50) DEFAULT NULL,
  `status` enum('planned','partial_issued','fully_issued','consumed') NOT NULL DEFAULT 'planned',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `item_id` (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 6. Production Order Bundles (QR/Barcode Tracking)
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_bundles` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `bundle_no` varchar(50) NOT NULL,
  `qr_code` varchar(255) DEFAULT NULL,
  `barcode` varchar(100) DEFAULT NULL,
  `color` varchar(50) DEFAULT NULL,
  `size` varchar(20) DEFAULT NULL,
  `quantity` int unsigned NOT NULL DEFAULT 0,
  `completed_qty` int unsigned NOT NULL DEFAULT 0,
  `rejected_qty` int unsigned NOT NULL DEFAULT 0,
  `current_operation_id` int unsigned DEFAULT NULL COMMENT 'production_order_operations.id',
  `current_station` varchar(100) DEFAULT NULL,
  `status` enum('created','in_process','at_qc','completed','rejected','packed') NOT NULL DEFAULT 'created',
  `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 `bundle_no` (`bundle_no`, `company_id`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `current_operation_id` (`current_operation_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 7. Production Order QC (Quality Checkpoints)
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_qc` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `operation_id` int unsigned DEFAULT NULL COMMENT 'production_order_operations.id',
  `bundle_id` int unsigned DEFAULT NULL COMMENT 'production_order_bundles.id',
  `inspection_type` enum('inline','midline','endline','final','random') NOT NULL DEFAULT 'inline',
  `inspector_name` varchar(150) DEFAULT NULL,
  `sample_size` int unsigned DEFAULT 0,
  `passed_qty` int unsigned DEFAULT 0,
  `rejected_qty` int unsigned DEFAULT 0,
  `defects` json DEFAULT NULL COMMENT '[{defect, count, severity}]',
  `result` enum('pass','fail','pending') NOT NULL DEFAULT 'pending',
  `remarks` text,
  `inspected_at` datetime 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`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `operation_id` (`operation_id`),
  KEY `bundle_id` (`bundle_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 8. Production Order WIP (Work In Progress Snapshot)
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_wip` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `operation_id` int unsigned DEFAULT NULL,
  `snapshot_date` date NOT NULL,
  `qty_at_station` int unsigned NOT NULL DEFAULT 0,
  `qty_completed` int unsigned NOT NULL DEFAULT 0,
  `qty_rejected` int unsigned NOT NULL DEFAULT 0,
  `wait_time_hours` decimal(6,2) DEFAULT 0,
  `efficiency_pct` decimal(5,2) DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `snapshot_date` (`snapshot_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 9. Production Order Labor
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_labor` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `operation_id` int unsigned DEFAULT NULL,
  `worker_name` varchar(150) DEFAULT NULL,
  `worker_id` varchar(50) DEFAULT NULL,
  `role` enum('operator','helper','supervisor','qc') DEFAULT 'operator',
  `shift` enum('day','night','general') DEFAULT 'day',
  `hours_worked` decimal(6,2) DEFAULT 0,
  `pieces_produced` int unsigned DEFAULT 0,
  `rate_per_hour` decimal(10,2) DEFAULT 0,
  `total_cost` decimal(10,2) DEFAULT 0,
  `date` date DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `operation_id` (`operation_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 10. Production Order Machine Logs
-- ============================================================
CREATE TABLE IF NOT EXISTS `production_order_machine_logs` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `prod_order_id` int unsigned NOT NULL,
  `operation_id` int unsigned DEFAULT NULL,
  `work_center_id` int unsigned DEFAULT NULL,
  `machine_status` enum('running','idle','breakdown','maintenance') NOT NULL DEFAULT 'running',
  `start_time` datetime DEFAULT NULL,
  `end_time` datetime DEFAULT NULL,
  `runtime_minutes` int unsigned DEFAULT 0,
  `downtime_minutes` int unsigned DEFAULT 0,
  `downtime_reason` varchar(255) DEFAULT NULL,
  `operator_name` varchar(150) DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `prod_order_id` (`prod_order_id`),
  KEY `work_center_id` (`work_center_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ============================================================
-- PROCESS ORDERS (Batch / Process Manufacturing)
-- ============================================================

-- ============================================================
-- 11. Process Orders
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_no` varchar(30) NOT NULL,
  `order_type` enum('dyeing','washing','compacting','knitting','finishing','heat_setting','mercerizing','coating','subcontract','rework','other') NOT NULL DEFAULT 'dyeing',
  `buyer_po_id` int unsigned DEFAULT NULL,
  `style_id` int unsigned DEFAULT NULL,
  `material_name` varchar(255) DEFAULT NULL COMMENT 'e.g. Cotton Jersey, Polyester Twill',
  `fabric_type` varchar(100) DEFAULT NULL,
  `batch_no` varchar(50) DEFAULT NULL,
  `planned_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `completed_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `rejected_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `uom` varchar(20) DEFAULT 'Kg',
  `color` varchar(50) DEFAULT NULL,
  `shade` varchar(50) DEFAULT NULL,
  `recipe_id` int unsigned DEFAULT NULL,
  `machine_id` int unsigned DEFAULT NULL COMMENT 'master_work_centers.id',
  `factory_id` int unsigned DEFAULT NULL,
  `planned_start_date` date DEFAULT NULL,
  `planned_end_date` date DEFAULT NULL,
  `actual_start_date` date DEFAULT NULL,
  `actual_end_date` date DEFAULT NULL,
  `priority` enum('low','medium','high','urgent') NOT NULL DEFAULT 'medium',
  `status` enum('draft','planned','released','in_progress','paused','completed','closed','cancelled') NOT NULL DEFAULT 'draft',
  `completion_pct` decimal(5,2) NOT NULL DEFAULT 0,
  `estimated_cost` decimal(12,2) DEFAULT 0,
  `actual_cost` decimal(12,2) DEFAULT 0,
  `shrinkage_pct` decimal(5,2) DEFAULT 0,
  `weight_loss_pct` decimal(5,2) DEFAULT 0,
  `ph_level` decimal(4,1) DEFAULT NULL,
  `notes` text,
  `created_by` int unsigned DEFAULT NULL,
  `approved_by` int unsigned DEFAULT NULL,
  `approved_at` datetime DEFAULT NULL,
  `released_at` datetime 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 `process_order_no` (`process_order_no`, `company_id`),
  KEY `company_id` (`company_id`),
  KEY `buyer_po_id` (`buyer_po_id`),
  KEY `style_id` (`style_id`),
  KEY `machine_id` (`machine_id`),
  KEY `factory_id` (`factory_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 12. Process Order Recipes (Chemical/Material Formulation)
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_recipes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `recipe_name` varchar(255) DEFAULT NULL,
  `material_name` varchar(255) NOT NULL,
  `material_type` enum('chemical','dye','water','salt','softener','agent','auxiliary','other') DEFAULT 'chemical',
  `concentration` decimal(8,2) DEFAULT NULL COMMENT 'g/L or %',
  `required_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `actual_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `uom` varchar(20) DEFAULT 'Kg',
  `rate` decimal(12,2) DEFAULT 0,
  `total_cost` decimal(12,2) DEFAULT 0,
  `sequence` int unsigned NOT NULL DEFAULT 0,
  `addition_time_min` int unsigned DEFAULT NULL COMMENT 'Minutes from start',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 13. Process Order Operations (Process Steps)
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_operations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `sequence` int unsigned NOT NULL DEFAULT 10,
  `operation_name` varchar(150) NOT NULL,
  `machine_id` int unsigned DEFAULT NULL COMMENT 'master_work_centers.id',
  `machine_name` varchar(150) DEFAULT NULL,
  `target_temp_c` decimal(5,1) DEFAULT NULL COMMENT 'Target temperature in Celsius',
  `actual_temp_c` decimal(5,1) DEFAULT NULL,
  `target_duration_min` int unsigned DEFAULT NULL COMMENT 'Duration in minutes',
  `actual_duration_min` int unsigned DEFAULT NULL,
  `target_ph` decimal(4,1) DEFAULT NULL,
  `actual_ph` decimal(4,1) DEFAULT NULL,
  `speed_rpm` decimal(8,2) DEFAULT NULL,
  `liquor_ratio` varchar(20) DEFAULT NULL COMMENT 'e.g. 1:8',
  `planned_start_date` date DEFAULT NULL,
  `planned_end_date` date DEFAULT NULL,
  `actual_start_date` date DEFAULT NULL,
  `actual_end_date` date DEFAULT NULL,
  `status` enum('pending','in_progress','completed','on_hold','skipped') NOT NULL DEFAULT 'pending',
  `operator_name` varchar(150) DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `machine_id` (`machine_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 14. Process Order Batches (Batch Tracking)
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_batches` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `batch_no` varchar(50) NOT NULL,
  `input_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `output_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `rejected_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `shrinkage_pct` decimal(5,2) DEFAULT 0,
  `status` enum('created','in_process','completed','rejected') NOT NULL DEFAULT 'created',
  `started_at` datetime DEFAULT NULL,
  `completed_at` datetime DEFAULT NULL,
  `notes` text,
  `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 `batch_no` (`batch_no`, `company_id`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 15. Process Order Consumption (Actual Material Usage)
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_consumption` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `batch_id` int unsigned DEFAULT NULL,
  `recipe_id` int unsigned DEFAULT NULL,
  `material_name` varchar(255) NOT NULL,
  `planned_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `actual_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `uom` varchar(20) DEFAULT 'Kg',
  `warehouse_id` int unsigned DEFAULT NULL,
  `batch_no` varchar(50) DEFAULT NULL,
  `issued_at` datetime DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `batch_id` (`batch_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 16. Process Order Output (Yield Tracking)
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_output` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `batch_id` int unsigned DEFAULT NULL,
  `output_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `output_uom` varchar(20) DEFAULT 'Kg',
  `quality_grade` enum('a','b','c','rejected') DEFAULT 'a',
  `shrinkage_pct` decimal(5,2) DEFAULT 0,
  `color_fastness` varchar(50) DEFAULT NULL,
  `ph_value` decimal(4,1) DEFAULT NULL,
  `gsm_after` decimal(8,2) DEFAULT NULL,
  `destination_warehouse_id` int unsigned DEFAULT NULL,
  `received_at` datetime DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `batch_id` (`batch_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 17. Process Order Quality (Quality Parameters)
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_quality` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `batch_id` int unsigned DEFAULT NULL,
  `inspection_type` enum('in_process','final','random') NOT NULL DEFAULT 'final',
  `inspector_name` varchar(150) DEFAULT NULL,
  `color_shade` varchar(50) DEFAULT NULL,
  `color_fastness_wash` varchar(20) DEFAULT NULL,
  `color_fastness_rub` varchar(20) DEFAULT NULL,
  `color_fastness_light` varchar(20) DEFAULT NULL,
  `shrinkage_pct` decimal(5,2) DEFAULT NULL,
  `gsm` decimal(8,2) DEFAULT NULL,
  `ph_value` decimal(4,1) DEFAULT NULL,
  `strength_n` decimal(8,2) DEFAULT NULL COMMENT 'Bursting strength in Newtons',
  `hand_feel` varchar(50) DEFAULT NULL,
  `pilling_rating` varchar(20) DEFAULT NULL,
  `result` enum('pass','conditional','fail','pending') NOT NULL DEFAULT 'pending',
  `remarks` text,
  `inspected_at` datetime 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`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `batch_id` (`batch_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 18. Process Order Machine Logs
-- ============================================================
CREATE TABLE IF NOT EXISTS `process_order_machine_logs` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `process_order_id` int unsigned NOT NULL,
  `operation_id` int unsigned DEFAULT NULL,
  `machine_id` int unsigned DEFAULT NULL,
  `machine_status` enum('running','idle','breakdown','maintenance','cleaning') NOT NULL DEFAULT 'running',
  `start_time` datetime DEFAULT NULL,
  `end_time` datetime DEFAULT NULL,
  `runtime_minutes` int unsigned DEFAULT 0,
  `downtime_minutes` int unsigned DEFAULT 0,
  `downtime_reason` varchar(255) DEFAULT NULL,
  `temperature_c` decimal(5,1) DEFAULT NULL,
  `pressure_bar` decimal(6,2) DEFAULT NULL,
  `operator_name` varchar(150) DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `machine_id` (`machine_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 19. Manufacturing Orders (Unified View - Virtual/Reference Table)
-- The app uses production_orders + process_orders as backends
-- This table is optional for unified tracking
-- ============================================================
CREATE TABLE IF NOT EXISTS `manufacturing_orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `mfg_order_no` varchar(30) NOT NULL,
  `order_type` enum('production','process','subcontract','rework','sample','maintenance') NOT NULL,
  `production_order_id` int unsigned DEFAULT NULL,
  `process_order_id` int unsigned DEFAULT NULL,
  `buyer_po_id` int unsigned DEFAULT NULL,
  `style_id` int unsigned DEFAULT NULL,
  `status` enum('draft','planned','released','in_progress','paused','completed','closed','cancelled') NOT NULL DEFAULT 'draft',
  `priority` enum('low','medium','high','urgent') NOT NULL DEFAULT 'medium',
  `planned_start_date` date DEFAULT NULL,
  `planned_end_date` date DEFAULT NULL,
  `completion_pct` decimal(5,2) NOT NULL DEFAULT 0,
  `notes` text,
  `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 `mfg_order_no` (`mfg_order_no`, `company_id`),
  KEY `company_id` (`company_id`),
  KEY `production_order_id` (`production_order_id`),
  KEY `process_order_id` (`process_order_id`),
  KEY `buyer_po_id` (`buyer_po_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ============================================================
-- FILE: seed_manufacturing_hm101.sql
-- ============================================================

-- ============================================================
-- SEED DATA: Manufacturing Orders for PO-HM-2024-001
-- PO: 12,000 Basic Cotton T-Shirts (Black), Sizes S/M/L/XL
-- Delivery: Aug 29, 2026 (ETD) / Sep 29, 2026 (ETA)
-- ============================================================

-- ========================================
-- 1. MASTER DATA: Production Lines
-- ========================================
INSERT IGNORE INTO master_production_lines (company_id, factory_id, line_name, line_code, capacity_per_day, section, status, notes) VALUES
(1, 1, 'Sewing Line A - T-Shirt', 'SL-A', 1200, 'sewing', 'active', 'Main t-shirt production line, 30 operators'),
(1, 1, 'Sewing Line B - T-Shirt', 'SL-B', 1000, 'sewing', 'active', 'Secondary t-shirt line, 25 operators'),
(1, 1, 'Cutting Section', 'CS-1', 5000, 'cutting', 'active', 'Auto spreading + manual cutting'),
(1, 1, 'Finishing & Packing', 'FP-1', 3000, 'finishing', 'active', 'Iron, fold, polybag, carton'),
(1, 3, 'Dyeing Line 1', 'DL-1', 2000, 'dyeing', 'active', 'Jet dyeing machine, 2000kg capacity'),
(1, 3, 'Washing Line 1', 'WL-1', 1500, 'washing', 'active', 'Industrial washing, enzyme wash capable');

-- ========================================
-- 2. MASTER DATA: Work Centers / Machines
-- ========================================
INSERT IGNORE INTO master_work_centers (company_id, factory_id, line_id, work_center_name, work_center_code, machine_type, category, hourly_rate, capacity_per_hour, status, notes) VALUES
(1, 1, 3, 'Auto Spreader SM-200', 'CUT-01', 'Auto Spreader', 'cutting', 15.00, 500.00, 'available', 'Gerber spreader, 200cm width'),
(1, 1, 3, 'Straight Knife LK-3', 'CUT-02', 'Straight Knife', 'cutting', 8.00, 150.00, 'available', 'Eastman straight knife cutter'),
(1, 1, 1, 'Overlock 5-Thread Juki', 'SEW-01', 'Overlock 5-thread', 'sewing', 12.00, 25.00, 'available', 'Juki MO-6814S'),
(1, 1, 1, 'Overlock 5-Thread Juki', 'SEW-02', 'Overlock 5-thread', 'sewing', 12.00, 25.00, 'in_use', 'Juki MO-6814S'),
(1, 1, 1, 'Coverstitch Juki', 'SEW-03', 'Coverstitch', 'sewing', 14.00, 22.00, 'available', 'Juki W4-100'),
(1, 1, 1, 'Coverstitch Juki', 'SEW-04', 'Coverstitch', 'sewing', 14.00, 22.00, 'in_use', 'Juki W4-100'),
(1, 1, 1, 'Single Needle Juki', 'SEW-05', 'Single Needle', 'sewing', 10.00, 30.00, 'available', 'Juki DDL-8100'),
(1, 1, 2, 'Overlock 5-Thread Juki', 'SEW-06', 'Overlock 5-thread', 'sewing', 12.00, 25.00, 'available', 'Backup line'),
(1, 1, 4, 'Steam Iron Station', 'FIN-01', 'Steam Iron', 'finishing', 8.00, 40.00, 'available', 'Industrial steam iron'),
(1, 3, 5, 'Jet Dyeing Machine 2T', 'DYE-01', 'Jet Dyeing Machine', 'dyeing', 50.00, 80.00, 'available', 'Thies iCone 2000kg'),
(1, 3, 5, 'Jet Dyeing Machine 1T', 'DYE-02', 'Jet Dyeing Machine', 'dyeing', 35.00, 45.00, 'in_use', 'Thies iCone 1000kg'),
(1, 3, 6, 'Industrial Washer BF-120', 'WASH-01', 'Industrial Washer', 'washing', 25.00, 60.00, 'available', 'Braun 120kg');

-- ========================================
-- 3. PRODUCTION ORDERS
-- ========================================

INSERT IGNORE INTO production_orders (company_id, prod_order_no, order_type, buyer_po_id, style_id, color, size, description,
  planned_qty, completed_qty, rejected_qty, scrapped_qty, uom, factory_id, line_id, work_center_id,
  planned_start_date, planned_end_date, actual_start_date, actual_end_date,
  priority, status, completion_pct, total_smv, total_sam, estimated_cost, actual_cost, notes, created_by) VALUES
(1, 'PROD-2026-000001', 'production', 1, 1, 'Black', '30', 'Batch 1: Size 30, 4000 pcs for Jakarta shipment',
 4000, 4000, 45, 0, 'PCS', 1, 1, 5, '2026-07-15', '2026-08-05', '2026-07-15', '2026-08-02',
 'high', 'completed', 100.00, 5.25, 5.25, 33600.00, 32800.00, 'First batch — size 30. Jakarta delivery.', 1),
(1, 'PROD-2026-000002', 'production', 1, 1, 'Black', '32', 'Batch 2: Size 32, 4000 pcs for Colombo shipment',
 4000, 3650, 38, 0, 'PCS', 1, 1, 5, '2026-07-20', '2026-08-12', '2026-07-20', NULL,
 'high', 'in_progress', 91.25, 5.25, 5.25, 33600.00, 30450.00, 'Second batch — size 32 in progress.', 1),
(1, 'PROD-2026-000003', 'production', 1, 1, 'Black', '34', 'Batch 3: Size 34, 4000 pcs for Barcelona shipment',
 4000, 2100, 22, 0, 'PCS', 1, 2, 6, '2026-08-01', '2026-08-20', '2026-08-01', NULL,
 'medium', 'in_progress', 52.50, 5.25, 5.25, 33600.00, 17640.00, 'Third batch — size 34 mid-production.', 1);

-- ========================================
-- 4. PRODUCTION ORDER OPERATIONS
-- ========================================

-- PROD-1 (COMPLETED — all 13 ops)
INSERT IGNORE INTO production_order_operations (company_id, prod_order_id, sequence, operation_name, operation_type, work_center_id, machine_type,
  planned_qty, completed_qty, rejected_qty, operators_required, smv, sam, planned_hours, actual_hours, status, actual_start_date, actual_end_date, notes) VALUES
(1, 1, 10, 'Front Panel Cut', 'cutting', 1, 'Straight Knife', 4000, 4000, 5, 2, 0.80, 0.80, 133.3, 128.5, 'completed', '2026-07-15', '2026-07-16', NULL),
(1, 1, 20, 'Back Panel Cut', 'cutting', 1, 'Straight Knife', 4000, 4000, 3, 2, 0.70, 0.70, 116.7, 112.0, 'completed', '2026-07-16', '2026-07-17', NULL),
(1, 1, 30, 'Sleeve Cut', 'cutting', 1, 'Straight Knife', 4000, 4000, 2, 2, 0.50, 0.50, 83.3, 80.0, 'completed', '2026-07-17', '2026-07-17', NULL),
(1, 1, 40, 'Shoulder Seam', 'sewing', 3, 'Overlock 5-thread', 4000, 4000, 8, 3, 0.45, 0.45, 75.0, 72.0, 'completed', '2026-07-18', '2026-07-19', NULL),
(1, 1, 50, 'Neck Collar Attach', 'sewing', 5, 'Coverstitch', 4000, 4000, 12, 3, 0.60, 0.60, 100.0, 96.0, 'completed', '2026-07-19', '2026-07-21', 'Rib collar binding'),
(1, 1, 60, 'Sleeve Set-in', 'sewing', 3, 'Overlock 5-thread', 4000, 4000, 6, 3, 0.75, 0.75, 125.0, 120.0, 'completed', '2026-07-21', '2026-07-23', NULL),
(1, 1, 70, 'Side Seam', 'sewing', 3, 'Overlock 5-thread', 4000, 4000, 4, 2, 0.55, 0.55, 91.7, 88.0, 'completed', '2026-07-23', '2026-07-24', NULL),
(1, 1, 80, 'Hem Bottom', 'sewing', 5, 'Coverstitch', 4000, 4000, 3, 2, 0.40, 0.40, 66.7, 64.0, 'completed', '2026-07-24', '2026-07-25', NULL),
(1, 1, 90, 'Sleeve Hem', 'sewing', 5, 'Coverstitch', 4000, 4000, 2, 2, 0.35, 0.35, 58.3, 56.0, 'completed', '2026-07-25', '2026-07-26', NULL),
(1, 1, 100, 'Label Attach', 'sewing', 7, 'Single Needle', 4000, 4000, 0, 1, 0.20, 0.20, 33.3, 32.0, 'completed', '2026-07-26', '2026-07-26', NULL),
(1, 1, 110, 'Trim & Thread Cut', 'finishing', 9, 'Manual', 4000, 4000, 0, 2, 0.30, 0.30, 50.0, 48.0, 'completed', '2026-07-27', '2026-07-28', NULL),
(1, 1, 120, 'Quality Check', 'quality', NULL, 'Manual', 4000, 4000, 45, 3, 0.40, 0.40, 66.7, 65.0, 'completed', '2026-07-28', '2026-07-29', '100% inline check'),
(1, 1, 130, 'Fold & Polybag', 'packing', NULL, 'Manual', 4000, 4000, 0, 4, 0.25, 0.25, 41.7, 40.0, 'completed', '2026-07-29', '2026-07-30', NULL);

-- PROD-2 (IN PROGRESS — at Sleeve Set-in)
INSERT IGNORE INTO production_order_operations (company_id, prod_order_id, sequence, operation_name, operation_type, work_center_id, machine_type,
  planned_qty, completed_qty, rejected_qty, operators_required, smv, sam, planned_hours, actual_hours, status, actual_start_date, actual_end_date, notes) VALUES
(1, 2, 10, 'Front Panel Cut', 'cutting', 1, 'Straight Knife', 4000, 4000, 3, 2, 0.80, 0.80, 133.3, 130.0, 'completed', '2026-07-20', '2026-07-21', NULL),
(1, 2, 20, 'Back Panel Cut', 'cutting', 1, 'Straight Knife', 4000, 4000, 4, 2, 0.70, 0.70, 116.7, 114.0, 'completed', '2026-07-21', '2026-07-22', NULL),
(1, 2, 30, 'Sleeve Cut', 'cutting', 1, 'Straight Knife', 4000, 4000, 2, 2, 0.50, 0.50, 83.3, 81.0, 'completed', '2026-07-22', '2026-07-23', NULL),
(1, 2, 40, 'Shoulder Seam', 'sewing', 3, 'Overlock 5-thread', 4000, 3800, 10, 3, 0.45, 0.45, 75.0, 72.0, 'completed', '2026-07-23', '2026-07-25', NULL),
(1, 2, 50, 'Neck Collar Attach', 'sewing', 5, 'Coverstitch', 4000, 3500, 8, 3, 0.60, 0.60, 100.0, 90.0, 'completed', '2026-07-25', '2026-07-27', 'Rib collar binding'),
(1, 2, 60, 'Sleeve Set-in', 'sewing', 3, 'Overlock 5-thread', 4000, 2800, 6, 3, 0.75, 0.75, 125.0, 85.0, 'in_progress', '2026-07-27', NULL, NULL),
(1, 2, 70, 'Side Seam', 'sewing', 3, 'Overlock 5-thread', 4000, 0, 0, 2, 0.55, 0.55, 91.7, NULL, 'pending', NULL, NULL, NULL),
(1, 2, 80, 'Hem Bottom', 'sewing', 5, 'Coverstitch', 4000, 0, 0, 2, 0.40, 0.40, 66.7, NULL, 'pending', NULL, NULL, NULL),
(1, 2, 90, 'Sleeve Hem', 'sewing', 5, 'Coverstitch', 4000, 0, 0, 2, 0.35, 0.35, 58.3, NULL, 'pending', NULL, NULL, NULL),
(1, 2, 100, 'Label Attach', 'sewing', 7, 'Single Needle', 4000, 0, 0, 1, 0.20, 0.20, 33.3, NULL, 'pending', NULL, NULL, NULL),
(1, 2, 110, 'Trim & Thread Cut', 'finishing', 9, 'Manual', 4000, 0, 0, 2, 0.30, 0.30, 50.0, NULL, 'pending', NULL, NULL, NULL),
(1, 2, 120, 'Quality Check', 'quality', NULL, 'Manual', 4000, 0, 0, 3, 0.40, 0.40, 66.7, NULL, 'pending', NULL, NULL, '100% inline check'),
(1, 2, 130, 'Fold & Polybag', 'packing', NULL, 'Manual', 4000, 0, 0, 4, 0.25, 0.25, 41.7, NULL, 'pending', NULL, NULL, NULL);

-- PROD-3 (IN PROGRESS — at Sleeve Cut)
INSERT IGNORE INTO production_order_operations (company_id, prod_order_id, sequence, operation_name, operation_type, work_center_id, machine_type,
  planned_qty, completed_qty, rejected_qty, operators_required, smv, sam, planned_hours, actual_hours, status, actual_start_date, actual_end_date, notes) VALUES
(1, 3, 10, 'Front Panel Cut', 'cutting', 2, 'Straight Knife', 4000, 4000, 2, 2, 0.80, 0.80, 133.3, 131.0, 'completed', '2026-08-01', '2026-08-02', NULL),
(1, 3, 20, 'Back Panel Cut', 'cutting', 2, 'Straight Knife', 4000, 4000, 3, 2, 0.70, 0.70, 116.7, 114.0, 'completed', '2026-08-02', '2026-08-03', NULL),
(1, 3, 30, 'Sleeve Cut', 'cutting', 2, 'Straight Knife', 4000, 3800, 2, 2, 0.50, 0.50, 83.3, 78.0, 'in_progress', '2026-08-03', NULL, NULL),
(1, 3, 40, 'Shoulder Seam', 'sewing', 4, 'Overlock 5-thread', 4000, 0, 0, 3, 0.45, 0.45, 75.0, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 50, 'Neck Collar Attach', 'sewing', 6, 'Coverstitch', 4000, 0, 0, 3, 0.60, 0.60, 100.0, NULL, 'pending', NULL, NULL, 'Rib collar binding'),
(1, 3, 60, 'Sleeve Set-in', 'sewing', 4, 'Overlock 5-thread', 4000, 0, 0, 3, 0.75, 0.75, 125.0, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 70, 'Side Seam', 'sewing', 4, 'Overlock 5-thread', 4000, 0, 0, 2, 0.55, 0.55, 91.7, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 80, 'Hem Bottom', 'sewing', 6, 'Coverstitch', 4000, 0, 0, 2, 0.40, 0.40, 66.7, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 90, 'Sleeve Hem', 'sewing', 6, 'Coverstitch', 4000, 0, 0, 2, 0.35, 0.35, 58.3, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 100, 'Label Attach', 'sewing', 7, 'Single Needle', 4000, 0, 0, 1, 0.20, 0.20, 33.3, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 110, 'Trim & Thread Cut', 'finishing', 9, 'Manual', 4000, 0, 0, 2, 0.30, 0.30, 50.0, NULL, 'pending', NULL, NULL, NULL),
(1, 3, 120, 'Quality Check', 'quality', NULL, 'Manual', 4000, 0, 0, 3, 0.40, 0.40, 66.7, NULL, 'pending', NULL, NULL, '100% inline check'),
(1, 3, 130, 'Fold & Polybag', 'packing', NULL, 'Manual', 4000, 0, 0, 4, 0.25, 0.25, 41.7, NULL, 'pending', NULL, NULL, NULL);

-- ========================================
-- 5. PRODUCTION ORDER MATERIALS
-- ========================================

INSERT IGNORE INTO production_order_materials (company_id, prod_order_id, item_id, material_name, material_type, color, size, uom,
  required_qty, issued_qty, consumed_qty, returned_qty, wastage_qty, rate, total_cost, warehouse_id, status, notes) VALUES
-- PROD-1 (consumed)
(1, 1, 1, '100% Combed Cotton Jersey 180gsm', 'fabric', 'Black', '30', 'Kg', 4800.00, 4900.00, 4680.00, 0, 220.00, 4.50, 22050.00, NULL, 'consumed', '1.2kg/pc + 5% wastage'),
(1, 1, NULL, 'Rib Neck Collar 1x1', 'trim', 'Black', '30', 'Kg', 600.00, 610.00, 590.00, 0, 20.00, 8.00, 4880.00, NULL, 'consumed', NULL),
(1, 1, NULL, 'Shoulder Tape 15mm', 'trim', 'Black', '30', 'Kg', 200.00, 205.00, 195.00, 0, 10.00, 2.50, 512.50, NULL, 'consumed', NULL),
(1, 1, NULL, 'Woven Label 30x50mm', 'accessory', 'Black', '30', 'Pcs', 4000, 4000, 4000, 0, 0, 0.12, 480.00, NULL, 'consumed', NULL),
(1, 1, NULL, 'Care Label SAT-001', 'accessory', 'Black', '30', 'Pcs', 4000, 4000, 4000, 0, 0, 0.08, 320.00, NULL, 'consumed', NULL),
(1, 1, NULL, 'Polybag 30x40cm', 'packaging', 'Black', '30', 'Pcs', 4000, 4000, 4000, 0, 0, 0.03, 120.00, NULL, 'consumed', NULL),
(1, 1, NULL, 'Carton Box 60x40x40cm', 'packaging', 'Black', '30', 'Pcs', 250, 250, 250, 0, 0, 0.85, 212.50, NULL, 'consumed', '16 pcs/carton'),
-- PROD-2 (partial)
(1, 2, 1, '100% Combed Cotton Jersey 180gsm', 'fabric', 'Black', '32', 'Kg', 4800.00, 4900.00, 4200.00, 0, 700.00, 4.50, 22050.00, NULL, 'partial_issued', NULL),
(1, 2, NULL, 'Rib Neck Collar 1x1', 'trim', 'Black', '32', 'Kg', 600.00, 610.00, 520.00, 0, 90.00, 8.00, 4880.00, NULL, 'partial_issued', NULL),
(1, 2, NULL, 'Shoulder Tape 15mm', 'trim', 'Black', '32', 'Kg', 200.00, 205.00, 175.00, 0, 30.00, 2.50, 512.50, NULL, 'partial_issued', NULL),
(1, 2, NULL, 'Woven Label 30x50mm', 'accessory', 'Black', '32', 'Pcs', 4000, 4000, 3650, 0, 0, 0.12, 480.00, NULL, 'partial_issued', NULL),
(1, 2, NULL, 'Care Label SAT-001', 'accessory', 'Black', '32', 'Pcs', 4000, 4000, 3650, 0, 0, 0.08, 320.00, NULL, 'partial_issued', NULL),
(1, 2, NULL, 'Polybag 30x40cm', 'packaging', 'Black', '32', 'Pcs', 4000, 2000, 0, 0, 0, 0.03, 120.00, NULL, 'partial_issued', 'Not yet packed'),
(1, 2, NULL, 'Carton Box 60x40x40cm', 'packaging', 'Black', '32', 'Pcs', 250, 0, 0, 0, 0, 0.85, 212.50, NULL, 'planned', NULL),
-- PROD-3 (partial)
(1, 3, 1, '100% Combed Cotton Jersey 180gsm', 'fabric', 'Black', '34', 'Kg', 4800.00, 4800.00, 2000.00, 0, 2800.00, 4.50, 21600.00, NULL, 'partial_issued', NULL),
(1, 3, NULL, 'Rib Neck Collar 1x1', 'trim', 'Black', '34', 'Kg', 600.00, 600.00, 250.00, 0, 350.00, 8.00, 4800.00, NULL, 'partial_issued', NULL),
(1, 3, NULL, 'Shoulder Tape 15mm', 'trim', 'Black', '34', 'Kg', 200.00, 200.00, 80.00, 0, 120.00, 2.50, 500.00, NULL, 'partial_issued', NULL),
(1, 3, NULL, 'Woven Label 30x50mm', 'accessory', 'Black', '34', 'Pcs', 4000, 4000, 2100, 0, 0, 0.12, 480.00, NULL, 'partial_issued', NULL),
(1, 3, NULL, 'Care Label SAT-001', 'accessory', 'Black', '34', 'Pcs', 4000, 4000, 2100, 0, 0, 0.08, 320.00, NULL, 'partial_issued', NULL),
(1, 3, NULL, 'Polybag 30x40cm', 'packaging', 'Black', '34', 'Pcs', 4000, 1000, 0, 0, 0, 0.03, 120.00, NULL, 'partial_issued', NULL),
(1, 3, NULL, 'Carton Box 60x40x40cm', 'packaging', 'Black', '34', 'Pcs', 250, 0, 0, 0, 0, 0.85, 212.50, NULL, 'planned', NULL);

-- ========================================
-- 6. BUNDLES (QR tracking)
-- ========================================

-- PROD-1 (20 bundles — all completed)
INSERT IGNORE INTO production_order_bundles (company_id, prod_order_id, bundle_no, qr_code, color, size, quantity, status) VALUES
(1, 1, 'B-20260715-0001', 'QR-PROD1-B001', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0002', 'QR-PROD1-B002', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0003', 'QR-PROD1-B003', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0004', 'QR-PROD1-B004', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0005', 'QR-PROD1-B005', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0006', 'QR-PROD1-B006', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0007', 'QR-PROD1-B007', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0008', 'QR-PROD1-B008', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0009', 'QR-PROD1-B009', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0010', 'QR-PROD1-B010', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0011', 'QR-PROD1-B011', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0012', 'QR-PROD1-B012', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0013', 'QR-PROD1-B013', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0014', 'QR-PROD1-B014', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0015', 'QR-PROD1-B015', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0016', 'QR-PROD1-B016', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0017', 'QR-PROD1-B017', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0018', 'QR-PROD1-B018', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0019', 'QR-PROD1-B019', 'Black', '30', 200, 'completed'),
(1, 1, 'B-20260715-0020', 'QR-PROD1-B020', 'Black', '30', 200, 'completed');

-- PROD-2 (20 bundles — mixed status)
INSERT IGNORE INTO production_order_bundles (company_id, prod_order_id, bundle_no, qr_code, color, size, quantity, status) VALUES
(1, 2, 'B-20260720-0001', 'QR-PROD2-B001', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0002', 'QR-PROD2-B002', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0003', 'QR-PROD2-B003', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0004', 'QR-PROD2-B004', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0005', 'QR-PROD2-B005', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0006', 'QR-PROD2-B006', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0007', 'QR-PROD2-B007', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0008', 'QR-PROD2-B008', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0009', 'QR-PROD2-B009', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0010', 'QR-PROD2-B010', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0011', 'QR-PROD2-B011', 'Black', '32', 200, 'completed'),
(1, 2, 'B-20260720-0012', 'QR-PROD2-B012', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0013', 'QR-PROD2-B013', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0014', 'QR-PROD2-B014', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0015', 'QR-PROD2-B015', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0016', 'QR-PROD2-B016', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0017', 'QR-PROD2-B017', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0018', 'QR-PROD2-B018', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0019', 'QR-PROD2-B019', 'Black', '32', 200, 'in_process'),
(1, 2, 'B-20260720-0020', 'QR-PROD2-B020', 'Black', '32', 200, 'in_process');

-- ========================================
-- 7. QC RECORDS
-- ========================================

INSERT IGNORE INTO production_order_qc (company_id, prod_order_id, operation_id, inspection_type, inspector_name, sample_size, passed_qty, rejected_qty, defects, result, remarks, inspected_at) VALUES
(1, 1, 50, 'inline', 'Rahim Uddin', 50, 48, 2, '[{"defect":"Open seam","count":1},{"defect":"Skip stitch","count":1}]', 'conditional', 'Minor open seam at shoulder, reworkable', '2026-07-19 14:30:00'),
(1, 1, 70, 'inline', 'Rahim Uddin', 50, 47, 3, '[{"defect":"Skip stitch","count":2},{"defect":"Puckering","count":1}]', 'conditional', 'Side seam puckering', '2026-07-23 15:00:00'),
(1, 1, 120, 'final', 'Fatima Begum', 200, 195, 5, '[{"defect":"Stain","count":2},{"defect":"Size deviation","count":2},{"defect":"Loose thread","count":1}]', 'passed', 'Final audit passed AQL 2.5', '2026-07-29 10:00:00'),
(1, 1, 120, 'final', 'Fatima Begum', 200, 198, 2, '[{"defect":"Loose thread","count":2}]', 'passed', NULL, '2026-07-29 11:30:00'),
(1, 1, 120, 'final', 'Fatima Begum', 200, 196, 4, '[{"defect":"Open seam","count":1},{"defect":"Label misaligned","count":2},{"defect":"Stain","count":1}]', 'passed', 'Within AQL limits', '2026-07-29 13:00:00'),
(1, 2, 40, 'inline', 'Rahim Uddin', 50, 49, 1, '[{"defect":"Skip stitch","count":1}]', 'passed', 'Good quality', '2026-07-25 14:00:00'),
(1, 2, 50, 'inline', 'Rahim Uddin', 50, 48, 2, '[{"defect":"Puckering","count":1},{"defect":"Open seam","count":1}]', 'conditional', 'Collar needs rework on 2 pcs', '2026-07-27 10:30:00');

-- ========================================
-- 8. WIP SNAPSHOTS
-- ========================================

INSERT IGNORE INTO production_order_wip (company_id, prod_order_id, operation_id, snapshot_date, qty_at_station, qty_completed, qty_rejected, wait_time_hours, efficiency_pct, notes) VALUES
(1, 2, 10, '2026-08-01', 0, 3996, 4, 0, 95.50, 'Cutting complete'),
(1, 2, 40, '2026-08-01', 0, 3990, 10, 0, 92.30, 'Shoulder seam complete'),
(1, 2, 50, '2026-08-01', 0, 3500, 8, 0, 88.50, 'Collar attach complete'),
(1, 2, 60, '2026-08-01', 1200, 2800, 6, 2.5, 85.00, 'Sleeve set-in in progress'),
(1, 2, 70, '2026-08-01', 0, 0, 0, 0, NULL, 'Waiting'),
(1, 2, 120, '2026-08-01', 0, 0, 0, 0, NULL, 'No QC yet');

-- ========================================
-- 9. LABOR RECORDS
-- ========================================

INSERT IGNORE INTO production_order_labor (company_id, prod_order_id, operation_id, worker_name, worker_id, role, shift, hours_worked, pieces_produced, rate_per_hour, total_cost, date) VALUES
(1, 1, 40, 'Kamal Hossain', 'OPR-001', 'operator', 'day', 8.0, 80, 3.50, 28.00, '2026-07-18'),
(1, 1, 40, 'Nasrin Akter', 'OPR-002', 'operator', 'day', 8.0, 75, 3.50, 28.00, '2026-07-18'),
(1, 1, 40, 'Jamal Miah', 'OPR-003', 'operator', 'day', 8.0, 78, 3.50, 28.00, '2026-07-18'),
(1, 1, 50, 'Rafiq Hasan', 'OPR-004', 'operator', 'day', 8.0, 65, 4.00, 32.00, '2026-07-19'),
(1, 1, 50, 'Salma Khatun', 'OPR-005', 'operator', 'day', 8.0, 62, 4.00, 32.00, '2026-07-19'),
(1, 1, 50, 'Abdul Hamid', 'OPR-006', 'operator', 'day', 8.0, 68, 4.00, 32.00, '2026-07-19'),
(1, 1, 120, 'Fatima Begum', 'QC-001', 'inspector', 'day', 8.0, NULL, 4.50, 36.00, '2026-07-29'),
(1, 1, 120, 'Rahim Uddin', 'QC-002', 'inspector', 'day', 8.0, NULL, 4.50, 36.00, '2026-07-29'),
(1, 2, 40, 'Kamal Hossain', 'OPR-001', 'operator', 'day', 8.0, 72, 3.50, 28.00, '2026-07-23'),
(1, 2, 40, 'Nasrin Akter', 'OPR-002', 'operator', 'day', 8.0, 70, 3.50, 28.00, '2026-07-23'),
(1, 2, 60, 'Jamal Miah', 'OPR-003', 'operator', 'day', 8.0, 60, 3.50, 28.00, '2026-07-28'),
(1, 2, 60, 'Rafiq Hasan', 'OPR-004', 'operator', 'day', 8.0, 58, 4.00, 32.00, '2026-07-28');

-- ========================================
-- 10. MACHINE LOGS (Production)
-- ========================================

INSERT IGNORE INTO production_order_machine_logs (company_id, prod_order_id, operation_id, work_center_id, machine_status, start_time, end_time, runtime_minutes, downtime_minutes, downtime_reason, operator_name, notes) VALUES
(1, 1, 10, 2, 'running', '2026-07-15 08:00:00', '2026-07-15 18:00:00', 540, 60, 'Lunch break', 'Kamal Hossain', NULL),
(1, 1, 10, 2, 'maintenance', '2026-07-15 14:00:00', '2026-07-15 14:30:00', 0, 30, 'Blade sharpening', 'Kamal Hossain', NULL),
(1, 1, 40, 3, 'running', '2026-07-18 08:00:00', '2026-07-18 18:00:00', 540, 60, 'Lunch break', 'Kamal Hossain', NULL),
(1, 1, 50, 5, 'running', '2026-07-19 08:00:00', '2026-07-19 18:00:00', 540, 60, 'Lunch break', 'Rafiq Hasan', NULL),
(1, 1, 50, 5, 'idle', '2026-07-19 11:00:00', '2026-07-19 11:20:00', 0, 20, 'Thread break', 'Rafiq Hasan', 'Re-threaded coverstitch'),
(1, 2, 40, 3, 'running', '2026-07-23 08:00:00', '2026-07-23 18:00:00', 540, 60, 'Lunch break', 'Kamal Hossain', NULL),
(1, 2, 60, 3, 'running', '2026-07-28 08:00:00', '2026-07-28 18:00:00', 540, 60, 'Lunch break', 'Jamal Miah', NULL),
(1, 2, 60, 3, 'idle', '2026-07-29 10:00:00', '2026-07-29 10:15:00', 0, 15, 'Needle break', 'Jamal Miah', NULL);

-- ========================================
-- 11. PROCESS ORDERS
-- ========================================

INSERT IGNORE INTO process_orders (company_id, process_order_no, order_type, buyer_po_id, style_id, material_name, fabric_type, batch_no,
  planned_qty, completed_qty, rejected_qty, uom, color, shade,
  machine_id, factory_id,
  planned_start_date, planned_end_date, actual_start_date, actual_end_date,
  priority, status, completion_pct, estimated_cost, actual_cost, shrinkage_pct, weight_loss_pct, ph_level,
  notes, created_by) VALUES
(1, 'PROC-2026-000001', 'dyeing', 1, 1, '100% Combed Cotton Jersey 180gsm', 'Single Jersey', 'DYE-BLK-001',
 14400.00, 14400.00, 0.00, 'Kg', 'Black', 'Jet Black', 11, 3,
 '2026-07-10', '2026-07-14', '2026-07-10', '2026-07-13',
 'high', 'completed', 100.00, 18000.00, 17500.00, 3.20, 1.80, 7.2,
 'All 12,000 pcs fabric dyed jet black. Reactive dye, 60C process.', 1),
(1, 'PROC-2026-000002', 'washing', 1, 1, '100% Combed Cotton Jersey 180gsm', 'Single Jersey', 'WASH-BLK-001',
 14400.00, 14400.00, 0.00, 'Kg', 'Black', 'Jet Black', 12, 3,
 '2026-07-14', '2026-07-15', '2026-07-14', '2026-07-15',
 'high', 'completed', 100.00, 8000.00, 7800.00, 2.10, 1.20, 6.8,
 'Enzyme wash + compacting completed. Hand-feel improved.', 1),
(1, 'PROC-2026-000003', 'dyeing', 1, 1, '100% Combed Cotton Jersey 180gsm', 'Single Jersey', 'DYE-BLK-002',
 5000.00, 3200.00, 50.00, 'Kg', 'Black', 'Jet Black', 12, 3,
 '2026-08-10', '2026-08-14', '2026-08-10', NULL,
 'medium', 'in_progress', 64.00, 6250.00, 4000.00, NULL, NULL, 7.0,
 'Second dye lot in progress — replenishment fabric.', 1);

-- ========================================
-- 12. PROCESS ORDER OPERATIONS
-- ========================================

-- PROC-1 (Dyeing — COMPLETED)
INSERT IGNORE INTO process_order_operations (company_id, process_order_id, sequence, operation_name, machine_id, machine_name,
  target_temp_c, actual_temp_c, target_duration_min, actual_duration_min, target_ph, actual_ph,
  speed_rpm, liquor_ratio, planned_start_date, planned_end_date, actual_start_date, actual_end_date,
  status, operator_name, notes) VALUES
(1, 1, 10, 'Fabric Loading', 11, 'Jet Dyeing Machine 2T', NULL, NULL, 30, 28, NULL, NULL, NULL, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', 'Loaded 14,400kg'),
(1, 1, 20, 'Pre-wash & Wetting', 11, 'Jet Dyeing Machine 2T', 40, 40, 15, 15, 7.0, 7.0, NULL, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', NULL),
(1, 1, 30, 'Dyeing Cycle', 11, 'Jet Dyeing Machine 2T', 60, 60, 120, 125, 11.0, 11.2, 35, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', 'Reactive black dye + salt + soda ash'),
(1, 1, 40, 'Hot Rinse', 11, 'Jet Dyeing Machine 2T', 80, 80, 30, 30, 7.0, 7.1, NULL, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', NULL),
(1, 1, 50, 'Soaping', 11, 'Jet Dyeing Machine 2T', 95, 95, 20, 22, 7.0, 7.0, NULL, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', NULL),
(1, 1, 60, 'Cold Rinse', 11, 'Jet Dyeing Machine 2T', 25, 25, 15, 15, 7.0, 7.0, NULL, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', NULL),
(1, 1, 70, 'Dye Fixation', 11, 'Jet Dyeing Machine 2T', 40, 40, 20, 20, 4.5, 4.5, NULL, '1:8', '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', NULL),
(1, 1, 80, 'Hydro-extraction', NULL, NULL, NULL, NULL, 10, 10, NULL, NULL, NULL, NULL, '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', NULL),
(1, 1, 90, 'Unloading & Inspection', NULL, NULL, NULL, NULL, 45, 40, NULL, NULL, NULL, NULL, '2026-07-10', '2026-07-10', '2026-07-10', '2026-07-10', 'completed', 'Kabir Rahman', 'Shade check');

-- PROC-2 (Washing — COMPLETED)
INSERT IGNORE INTO process_order_operations (company_id, process_order_id, sequence, operation_name, machine_id, machine_name,
  target_temp_c, actual_temp_c, target_duration_min, actual_duration_min, target_ph, actual_ph,
  speed_rpm, liquor_ratio, planned_start_date, planned_end_date, actual_start_date, actual_end_date,
  status, operator_name, notes) VALUES
(1, 2, 10, 'Fabric Loading', 13, 'Industrial Washer BF-120', NULL, NULL, 20, 18, NULL, NULL, NULL, '1:6', '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', NULL),
(1, 2, 20, 'Enzyme Wash', 13, 'Industrial Washer BF-120', 55, 55, 45, 48, 6.5, 6.5, 30, '1:6', '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', 'Cellulase enzyme'),
(1, 2, 30, 'Hot Rinse', 13, 'Industrial Washer BF-120', 60, 60, 15, 15, 7.0, 7.0, NULL, '1:6', '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', NULL),
(1, 2, 40, 'Softener Treatment', 13, 'Industrial Washer BF-120', 40, 40, 20, 20, 5.5, 5.5, NULL, '1:6', '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', 'Silicone softener'),
(1, 2, 50, 'Hydro-extraction', NULL, NULL, NULL, NULL, 10, 10, NULL, NULL, NULL, NULL, '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', NULL),
(1, 2, 60, 'Tumble Dry & Compact', NULL, NULL, 80, 80, 30, 35, NULL, NULL, NULL, NULL, '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', NULL),
(1, 2, 70, 'Inspection & Roll-up', NULL, NULL, NULL, NULL, 40, 35, NULL, NULL, NULL, NULL, '2026-07-14', '2026-07-14', '2026-07-14', '2026-07-14', 'completed', 'Monir Hossain', 'Shade approved');

-- PROC-3 (Dyeing — IN PROGRESS)
INSERT IGNORE INTO process_order_operations (company_id, process_order_id, sequence, operation_name, machine_id, machine_name,
  target_temp_c, actual_temp_c, target_duration_min, actual_duration_min, target_ph, actual_ph,
  speed_rpm, liquor_ratio, planned_start_date, planned_end_date, actual_start_date, actual_end_date,
  status, operator_name, notes) VALUES
(1, 3, 10, 'Fabric Loading', 11, 'Jet Dyeing Machine 2T', NULL, NULL, 20, 18, NULL, NULL, NULL, '1:8', '2026-08-10', '2026-08-10', '2026-08-10', '2026-08-10', 'completed', 'Kabir Rahman', NULL),
(1, 3, 20, 'Pre-wash & Wetting', 11, 'Jet Dyeing Machine 2T', 40, 40, 15, 14, 7.0, 7.0, NULL, '1:8', '2026-08-10', '2026-08-10', '2026-08-10', '2026-08-10', 'completed', 'Kabir Rahman', NULL),
(1, 3, 30, 'Dyeing Cycle', 11, 'Jet Dyeing Machine 2T', 60, 60, 120, NULL, 11.0, NULL, 35, '1:8', '2026-08-10', '2026-08-10', '2026-08-10', NULL, 'in_progress', 'Kabir Rahman', '50% complete'),
(1, 3, 40, 'Hot Rinse', 11, 'Jet Dyeing Machine 2T', 80, NULL, 30, NULL, 7.0, NULL, NULL, '1:8', '2026-08-10', '2026-08-10', NULL, NULL, 'pending', NULL, NULL),
(1, 3, 50, 'Soaping', 11, 'Jet Dyeing Machine 2T', 95, NULL, 20, NULL, 7.0, NULL, NULL, '1:8', '2026-08-10', '2026-08-10', NULL, NULL, 'pending', NULL, NULL),
(1, 3, 60, 'Cold Rinse', 11, 'Jet Dyeing Machine 2T', 25, NULL, 15, NULL, 7.0, NULL, NULL, '1:8', '2026-08-10', '2026-08-10', NULL, NULL, 'pending', NULL, NULL),
(1, 3, 70, 'Dye Fixation', 11, 'Jet Dyeing Machine 2T', 40, NULL, 20, NULL, 4.5, NULL, NULL, '1:8', '2026-08-10', '2026-08-10', NULL, NULL, 'pending', NULL, NULL),
(1, 3, 80, 'Hydro-extraction', NULL, NULL, NULL, NULL, 10, NULL, NULL, NULL, NULL, NULL, '2026-08-10', '2026-08-10', NULL, NULL, 'pending', NULL, NULL),
(1, 3, 90, 'Unloading & Inspection', NULL, NULL, NULL, NULL, 45, NULL, NULL, NULL, NULL, NULL, '2026-08-10', '2026-08-10', NULL, NULL, 'pending', NULL, NULL);

-- ========================================
-- 13. PROCESS ORDER RECIPES
-- ========================================

INSERT IGNORE INTO process_order_recipes (company_id, process_order_id, recipe_name, material_name, material_type, concentration, required_qty, actual_qty, uom, rate, total_cost, sequence, notes) VALUES
(1, 1, 'Reactive Dye Bath', 'Remazol Black B', 'dye', 2.50, 360.00, 362.50, 'Kg', 12.00, 4350.00, 10, '2.5% owf'),
(1, 1, 'Reactive Dye Bath', 'Glauber Salt', 'salt', 60.00, 8640.00, 8685.00, 'Kg', 0.30, 2605.50, 20, 'Electrolyte'),
(1, 1, 'Reactive Dye Bath', 'Soda Ash', 'chemical', 2.00, 288.00, 285.00, 'Kg', 0.50, 142.50, 30, 'Alkali'),
(1, 1, 'Reactive Dye Bath', 'Sequestering Agent', 'agent', 1.00, 144.00, 145.00, 'Kg', 2.00, 290.00, 40, NULL),
(1, 1, 'Reactive Dye Bath', 'Leveling Agent', 'auxiliary', 0.50, 72.00, 73.00, 'Kg', 4.00, 292.00, 50, NULL),
(1, 1, 'Fixation', 'Dye Fixative', 'chemical', 2.00, 288.00, 290.00, 'Kg', 3.50, 1015.00, 60, NULL),
(1, 1, 'Soaping', 'Soaping Agent', 'chemical', 1.00, 144.00, 146.00, 'Kg', 2.50, 365.00, 70, NULL),
(1, 2, 'Enzyme Wash', 'Cellulase Enzyme', 'chemical', 0.50, 72.00, 72.50, 'Kg', 8.00, 580.00, 10, 'Bio-polish'),
(1, 2, 'Enzyme Wash', 'Acetic Acid', 'chemical', 0.30, 43.20, 44.00, 'Kg', 1.50, 66.00, 20, 'pH buffer'),
(1, 2, 'Softener', 'Silicone Softener', 'chemical', 3.00, 432.00, 435.00, 'Kg', 4.00, 1740.00, 30, 'Hand-feel'),
(1, 2, 'Softener', 'Anti-crease Agent', 'auxiliary', 1.00, 144.00, 143.00, 'Kg', 2.50, 357.50, 40, NULL);

-- ========================================
-- 14. PROCESS ORDER BATCHES
-- ========================================

INSERT IGNORE INTO process_order_batches (company_id, process_order_id, batch_no, input_qty, output_qty, rejected_qty, shrinkage_pct, status, started_at, completed_at, notes) VALUES
(1, 1, 'DYE-BLK-001-B1', 4800.00, 4680.00, 0, 2.50, 'completed', '2026-07-10 08:00', '2026-07-10 14:00', 'Sizes S/M'),
(1, 1, 'DYE-BLK-001-B2', 4800.00, 4700.00, 0, 2.08, 'completed', '2026-07-11 08:00', '2026-07-11 14:00', 'Size L'),
(1, 1, 'DYE-BLK-001-B3', 4800.00, 4690.00, 0, 2.29, 'completed', '2026-07-12 08:00', '2026-07-12 14:00', 'Size XL'),
(1, 2, 'WASH-BLK-001-B1', 7200.00, 7100.00, 0, 1.39, 'completed', '2026-07-14 08:00', '2026-07-14 14:00', 'First half'),
(1, 2, 'WASH-BLK-001-B2', 7200.00, 7120.00, 0, 1.11, 'completed', '2026-07-14 14:00', '2026-07-14 20:00', 'Second half'),
(1, 3, 'DYE-BLK-002-B1', 2500.00, 1600.00, 25.00, NULL, 'in_process', '2026-08-10 08:00', NULL, 'In dyeing cycle'),
(1, 3, 'DYE-BLK-002-B2', 2500.00, 1600.00, 25.00, NULL, 'in_process', '2026-08-10 08:00', NULL, 'Parallel batch');

-- ========================================
-- 15. PROCESS ORDER CONSUMPTION
-- ========================================

INSERT IGNORE INTO process_order_consumption (company_id, process_order_id, batch_id, material_name, planned_qty, actual_qty, uom, batch_no, notes) VALUES
(1, 1, 1, 'Remazol Black B', 120.00, 122.50, 'Kg', 'DYE-BLK-001-B1', 'Slight overdye'),
(1, 1, 1, 'Glauber Salt', 2880.00, 2900.00, 'Kg', 'DYE-BLK-001-B1', NULL),
(1, 1, 1, 'Soda Ash', 96.00, 95.00, 'Kg', 'DYE-BLK-001-B1', NULL),
(1, 1, 2, 'Remazol Black B', 120.00, 119.00, 'Kg', 'DYE-BLK-001-B2', NULL),
(1, 1, 2, 'Glauber Salt', 2880.00, 2890.00, 'Kg', 'DYE-BLK-001-B2', NULL),
(1, 1, 3, 'Remazol Black B', 120.00, 121.00, 'Kg', 'DYE-BLK-001-B3', NULL),
(1, 1, 3, 'Glauber Salt', 2880.00, 2895.00, 'Kg', 'DYE-BLK-001-B3', NULL),
(1, 2, 4, 'Cellulase Enzyme', 36.00, 37.50, 'Kg', 'WASH-BLK-001-B1', NULL),
(1, 2, 4, 'Silicone Softener', 216.00, 220.00, 'Kg', 'WASH-BLK-001-B1', NULL),
(1, 2, 5, 'Cellulase Enzyme', 36.00, 35.00, 'Kg', 'WASH-BLK-001-B2', NULL),
(1, 2, 5, 'Silicone Softener', 216.00, 215.00, 'Kg', 'WASH-BLK-001-B2', NULL);

-- ========================================
-- 16. PROCESS ORDER OUTPUT
-- ========================================

INSERT IGNORE INTO process_order_output (company_id, process_order_id, batch_id, output_qty, output_uom, quality_grade, shrinkage_pct, notes) VALUES
(1, 1, 1, 4680.00, 'Kg', 'a', 2.50, 'Excellent shade depth'),
(1, 1, 2, 4700.00, 'Kg', 'a', 2.08, 'Consistent with batch 1'),
(1, 1, 3, 4690.00, 'Kg', 'a', 2.29, 'All batches shade-matched'),
(1, 2, 4, 7100.00, 'Kg', 'a', 1.39, 'Good hand-feel'),
(1, 2, 5, 7120.00, 'Kg', 'a', 1.11, 'Excellent finish');

-- ========================================
-- 17. PROCESS ORDER QUALITY
-- ========================================

INSERT IGNORE INTO process_order_quality (company_id, process_order_id, batch_id, inspection_type, inspector_name,
  color_shade, color_fastness_wash, color_fastness_rub, color_fastness_light,
  shrinkage_pct, gsm, ph_value, hand_feel, pilling_rating, result, remarks, inspected_at) VALUES
(1, 1, 1, 'final', 'Nasrin Akter', 'Jet Black', '4-5', '3-4', '4', -3.0, 178, 7.2, 'Good', '4', 'pass', 'All parameters within tolerance', '2026-07-10 15:00:00'),
(1, 1, 2, 'final', 'Nasrin Akter', 'Jet Black', '4-5', '3-4', '4', -3.2, 177, 7.1, 'Good', '4', 'pass', 'Consistent with batch 1', '2026-07-11 15:00:00'),
(1, 1, 3, 'final', 'Nasrin Akter', 'Jet Black', '4-5', '3', '4', -2.8, 179, 7.3, 'Good', '4', 'pass', 'Shade-matched under D65', '2026-07-12 15:00:00'),
(1, 2, 4, 'final', 'Nasrin Akter', 'Jet Black', '4', '3', '3-4', -2.0, 175, 6.8, 'Excellent', '4', 'pass', 'Enzyme wash improved hand-feel', '2026-07-14 15:00:00'),
(1, 2, 5, 'final', 'Nasrin Akter', 'Jet Black', '4', '3', '3-4', -2.1, 174, 6.8, 'Excellent', '4', 'pass', 'Consistent with batch 1', '2026-07-14 21:00:00');

-- ========================================
-- 18. PROCESS ORDER MACHINE LOGS
-- ========================================

INSERT IGNORE INTO process_order_machine_logs (company_id, process_order_id, machine_id, machine_status, start_time, end_time, runtime_minutes, downtime_minutes, downtime_reason, operator_name, notes) VALUES
(1, 1, 11, 'running', '2026-07-10 08:00', '2026-07-10 14:00', 360, 0, NULL, 'Kabir Rahman', 'Batch 1'),
(1, 1, 11, 'running', '2026-07-11 08:00', '2026-07-11 14:00', 360, 0, NULL, 'Kabir Rahman', 'Batch 2'),
(1, 1, 11, 'maintenance', '2026-07-11 14:00', '2026-07-11 14:45', 0, 45, 'Pump seal replacement', 'Kabir Rahman', NULL),
(1, 1, 11, 'running', '2026-07-12 08:00', '2026-07-12 14:00', 360, 0, NULL, 'Kabir Rahman', 'Batch 3'),
(1, 2, 13, 'running', '2026-07-14 08:00', '2026-07-14 20:00', 720, 0, NULL, 'Monir Hossain', 'Both batches');


-- ============================================================
-- FILE: migration_asn_passport.sql
-- ============================================================

-- ============================================================
-- FashCognitive - ASN Digital Shipment Passport Migration
-- Enhances basic ASN into SAP-like EWM Shipment document
-- ============================================================

-- -----------------------------------------------------------
-- 1. Add new columns to asn table
-- -----------------------------------------------------------
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'asn' AND COLUMN_NAME = 'container_no');
SET @sql = IF(@col_exists = 0,
  'ALTER TABLE `asn`
    ADD COLUMN `container_no` varchar(100) DEFAULT NULL AFTER `invoice_no`,
    ADD COLUMN `seal_no` varchar(100) DEFAULT NULL AFTER `container_no`,
    ADD COLUMN `driver_name` varchar(255) DEFAULT NULL AFTER `seal_no`,
    ADD COLUMN `driver_mobile` varchar(50) DEFAULT NULL AFTER `driver_name`,
    ADD COLUMN `transporter_name` varchar(255) DEFAULT NULL AFTER `driver_mobile`,
    ADD COLUMN `shipping_mode` varchar(20) NOT NULL DEFAULT ''road'' AFTER `transporter_name`,
    ADD COLUMN `shipping_marks` text DEFAULT NULL AFTER `shipping_mode`,
    ADD COLUMN `total_pallets` int unsigned DEFAULT NULL AFTER `total_rolls`,
    ADD COLUMN `total_cartons` int unsigned DEFAULT NULL AFTER `total_pallets`,
    ADD COLUMN `total_weight_kg` decimal(14,2) DEFAULT NULL AFTER `total_cartons`,
    ADD COLUMN `total_volume_cbm` decimal(10,3) DEFAULT NULL AFTER `total_weight_kg`,
    ADD COLUMN `gate_entry_completed` tinyint(1) NOT NULL DEFAULT 0 AFTER `total_volume_cbm`,
    ADD COLUMN `gate_entry_at` datetime DEFAULT NULL AFTER `gate_entry_completed`,
    ADD COLUMN `dock_no` varchar(50) DEFAULT NULL AFTER `gate_entry_at`,
    ADD COLUMN `estimated_unloading_min` int unsigned DEFAULT NULL AFTER `dock_no`,
    ADD COLUMN `ai_readiness_score` decimal(5,2) DEFAULT NULL AFTER `estimated_unloading_min`,
    ADD COLUMN `ai_notes` text DEFAULT NULL AFTER `ai_readiness_score`,
    ADD COLUMN `created_by` int unsigned DEFAULT NULL AFTER `ai_notes`',
  'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- -----------------------------------------------------------
-- 2. ASN Documents (packing list, invoices, certificates, etc.)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `asn_documents` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `asn_id` int unsigned NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `file_path` varchar(500) NOT NULL,
  `file_type` varchar(100) DEFAULT NULL,
  `file_size` int unsigned DEFAULT 0,
  `category` enum('packing_list','commercial_invoice','eway_bill','test_certificate',
    'fabric_inspection','lab_report','transport_lr','certificate_of_origin',
    'insurance','other') NOT NULL DEFAULT 'other',
  `uploaded_by` int unsigned DEFAULT NULL,
  `uploaded_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_ad_asn` (`asn_id`),
  KEY `idx_ad_category` (`category`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 3. ASN Gate Entry (digital truck inspection)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `asn_gate_entry` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `asn_id` int unsigned NOT NULL,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `gate_entry_no` varchar(50) DEFAULT NULL,
  `entry_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `vehicle_verified` tinyint(1) NOT NULL DEFAULT 0,
  `seal_verified` tinyint(1) NOT NULL DEFAULT 0,
  `documents_verified` tinyint(1) NOT NULL DEFAULT 0,
  `invoice_verified` tinyint(1) NOT NULL DEFAULT 0,
  `packing_list_verified` tinyint(1) NOT NULL DEFAULT 0,
  `po_matched` tinyint(1) NOT NULL DEFAULT 0,
  `quantity_verified` tinyint(1) NOT NULL DEFAULT 0,
  `truck_photo` varchar(500) DEFAULT NULL,
  `driver_photo` varchar(500) DEFAULT NULL,
  `container_photo` varchar(500) DEFAULT NULL,
  `seal_photo` varchar(500) DEFAULT NULL,
  `gate_by` int unsigned DEFAULT NULL,
  `security_by` int unsigned DEFAULT NULL,
  `warehouse_by` int unsigned DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `status` enum('in_progress','completed','rejected') NOT NULL DEFAULT 'in_progress',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_age_asn` (`asn_id`),
  KEY `idx_age_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- -----------------------------------------------------------
-- 4. ASN Timeline (event log for full traceability)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS `asn_timeline` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `asn_id` int unsigned NOT NULL,
  `event_type` varchar(100) NOT NULL,
  `event_label` varchar(255) NOT NULL,
  `event_details` text DEFAULT NULL,
  `performed_by` int unsigned DEFAULT NULL,
  `event_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_at_asn` (`asn_id`),
  KEY `idx_at_event` (`event_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: seed_asn_grn_scorecards.sql
-- ============================================================

-- ============================================================
-- SEED DATA: ASN Digital Shipment Passport + GRN + Vendor Scorecards
-- ============================================================

-- ========================================
-- 1. ASN #2 — DRAFT (just created, not yet shipped)
-- ========================================
INSERT IGNORE INTO asn (id, company_id, asn_no, po_id, supplier_id, warehouse_id,
  ship_date, eta_date, vehicle_no, challan_no, invoice_no,
  total_boxes, total_rolls, total_pallets, total_cartons,
  total_weight_kg, total_volume_cbm, total_qty,
  gate_entry_completed, ai_readiness_score, ai_notes, created_by, status, notes) VALUES
(4, 1, 'ASN-2026-0002', 2, 4, 1,
  '2026-07-28', '2026-07-30', 'MH12DE3456', 'CH-2026-0891', 'INV-2026-789',
  0, 0, 0, 0,
  0, 0, 0,
  0, NULL, NULL, 1, 'draft', 'Waiting for supplier confirmation. Ready to ship.');

-- ASN #3 — IN_TRANSIT (shipped, ETA soon)
INSERT IGNORE INTO asn (id, company_id, asn_no, po_id, supplier_id, warehouse_id,
  ship_date, eta_date, vehicle_no, challan_no, invoice_no,
  container_no, seal_no, driver_name, driver_mobile, transporter_name,
  shipping_mode, shipping_marks, total_boxes, total_rolls, total_pallets, total_cartons,
  total_weight_kg, total_volume_cbm, total_qty,
  gate_entry_completed, ai_readiness_score, ai_notes, created_by, status, notes) VALUES
(5, 1, 'ASN-2026-0003', 1, 2, 2,
  '2026-07-18', '2026-07-22', 'DL01AB1234', 'CH-2026-0654', 'INV-2026-567',
  'MSKU7654321', 'SL-98765', 'Rajesh Kumar', '+919876543211', 'BlueStar Transport',
  'road', 'HANDLE WITH CARE', 45, 0, 4, 45,
  8500.00, 28.500, 15000.0000,
  0, 65.00, '{"readiness_score":65,"vehicle_loading":"Good","traffic_risk":"MEDIUM","late_delivery_risk":"LOW","suggested_dock":"Dock-1","estimated_unloading_min":50,"warehouse_capacity":"Available","recommendation":"Proceed with Standard Protocol","checks_passed":4,"checks_total":5}', 1, 'in_transit', 'Shipment picked up from supplier warehouse in Mumbai.');

-- ASN #4 — ARRIVED (fully processed through gate entry)
INSERT IGNORE INTO asn (id, company_id, asn_no, po_id, supplier_id, warehouse_id,
  ship_date, eta_date, actual_arrival, vehicle_no, challan_no, invoice_no,
  container_no, seal_no, driver_name, driver_mobile, transporter_name,
  shipping_mode, shipping_marks, total_boxes, total_rolls, total_pallets, total_cartons,
  total_weight_kg, total_volume_cbm, total_qty,
  gate_entry_completed, gate_entry_at, dock_no, estimated_unloading_min,
  ai_readiness_score, ai_notes, created_by, status, notes) VALUES
(6, 1, 'ASN-2026-0004', 1, 5, 3,
  '2026-07-15', '2026-07-18', '2026-07-18 09:30:00', 'GJ05CD7890', 'CH-2026-0321', 'INV-2026-234',
  'CMAU1234567', 'SL-54321', 'Mohammad Ali', '+919876543212', 'SwiftCargo Movers',
  'road', 'KEEP DRY - NO STACKING', 60, 0, 5, 60,
  12000.00, 38.400, 20000.0000,
  1, '2026-07-18 10:15:00', 'Dock-2', 45,
  92.00, '{"readiness_score":92,"vehicle_loading":"Excellent","traffic_risk":"LOW","late_delivery_risk":"NONE","suggested_dock":"Dock-2","estimated_unloading_min":45,"warehouse_capacity":"Available","recommendation":"Proceed with Standard Protocol","checks_passed":5,"checks_total":5}', 1, 'arrived', 'Full container load. All documents verified at gate.');

-- ASN #5 — RECEIVED (fully received + GRN created)
INSERT IGNORE INTO asn (id, company_id, asn_no, po_id, supplier_id, warehouse_id,
  ship_date, eta_date, actual_arrival, vehicle_no, challan_no, invoice_no,
  container_no, seal_no, driver_name, driver_mobile, transporter_name,
  shipping_mode, shipping_marks, total_boxes, total_rolls, total_pallets, total_cartons,
  total_weight_kg, total_volume_cbm, total_qty,
  gate_entry_completed, gate_entry_at, dock_no, estimated_unloading_min,
  ai_readiness_score, ai_notes, created_by, status, notes) VALUES
(7, 1, 'ASN-2026-0005', 2, 1, 1,
  '2026-07-10', '2026-07-13', '2026-07-13 08:00:00', 'KA01EF5678', 'CH-2026-0100', 'INV-2026-101',
  'TCNU8765432', 'SL-11223', 'Sunil Sharma', '+919876543213', 'National Logistics',
  'road', 'PO#2 - COTTON FABRIC', 40, 0, 3, 40,
  9800.00, 32.000, 16000.0000,
  1, '2026-07-13 09:00:00', 'Dock-1', 40,
  95.00, '{"readiness_score":95,"vehicle_loading":"Excellent","traffic_risk":"LOW","late_delivery_risk":"NONE","suggested_dock":"Dock-1","estimated_unloading_min":40,"warehouse_capacity":"Available","recommendation":"Proceed with Standard Protocol","checks_passed":5,"checks_total":5}', 1, 'received', 'Fabric received in excellent condition. GRN completed.');

-- ========================================
-- 2. ASN ITEMS
-- ========================================

-- ASN-2026-0003 (In Transit)
INSERT IGNORE INTO asn_items (asn_id, po_item_id, item_id, color, size, lot_no, batch_no, uom_id, shipped_qty, received_qty, boxes, rolls, notes) VALUES
(5, NULL, 1, 'Black', 'S', 'LOT-301', 'BAT-001', 5, 3000.0000, NULL, 8, 0, 'Cotton Jersey 180gsm - Size S'),
(5, NULL, 1, 'Black', 'M', 'LOT-302', 'BAT-001', 5, 4000.0000, NULL, 10, 0, 'Cotton Jersey 180gsm - Size M'),
(5, NULL, 1, 'Black', 'L', 'LOT-303', 'BAT-001', 5, 4000.0000, NULL, 10, 0, 'Cotton Jersey 180gsm - Size L'),
(5, NULL, 1, 'Black', 'XL', 'LOT-304', 'BAT-001', 5, 4000.0000, NULL, 10, 0, 'Cotton Jersey 180gsm - Size XL'),
(5, NULL, 3, 'White', NULL, 'LOT-305', 'BAT-002', 1, 10000.0000, NULL, 7, 0, 'Sewing Thread - Polyester');

-- ASN-2026-0004 (Arrived)
INSERT IGNORE INTO asn_items (asn_id, po_item_id, item_id, color, size, lot_no, batch_no, uom_id, shipped_qty, received_qty, boxes, rolls, notes) VALUES
(6, NULL, 1, 'Black', 'S', 'LOT-201', 'BAT-010', 5, 2500.0000, NULL, 6, 0, 'Cotton Jersey 180gsm - Size S'),
(6, NULL, 1, 'Black', 'M', 'LOT-202', 'BAT-010', 5, 3000.0000, NULL, 8, 0, 'Cotton Jersey 180gsm - Size M'),
(6, NULL, 1, 'Black', 'L', 'LOT-203', 'BAT-010', 5, 3500.0000, NULL, 8, 0, 'Cotton Jersey 180gsm - Size L'),
(6, NULL, 1, 'Black', 'XL', 'LOT-204', 'BAT-010', 5, 3500.0000, NULL, 8, 0, 'Cotton Jersey 180gsm - Size XL'),
(6, NULL, 2, 'Black', NULL, 'LOT-205', 'BAT-011', 5, 4000.0000, NULL, 10, 0, 'Rib Collar 1x1'),
(6, NULL, 3, 'Black', NULL, 'LOT-206', 'BAT-012', 1, 3500.0000, NULL, 20, 0, 'Sewing Thread');

-- ASN-2026-0005 (Received)
INSERT IGNORE INTO asn_items (asn_id, po_item_id, item_id, color, size, lot_no, batch_no, uom_id, shipped_qty, received_qty, boxes, rolls, notes) VALUES
(7, NULL, 1, 'Black', 'S', 'LOT-101', 'BAT-100', 5, 2000.0000, 2000.0000, 5, 0, 'Cotton Jersey - Size S - Received OK'),
(7, NULL, 1, 'Black', 'M', 'LOT-102', 'BAT-100', 5, 2000.0000, 2000.0000, 5, 0, 'Cotton Jersey - Size M - Received OK'),
(7, NULL, 1, 'Black', 'L', 'LOT-103', 'BAT-100', 5, 2000.0000, 2000.0000, 5, 0, 'Cotton Jersey - Size L - Received OK'),
(7, NULL, 1, 'Black', 'XL', 'LOT-104', 'BAT-100', 5, 2000.0000, 2000.0000, 5, 0, 'Cotton Jersey - Size XL - Received OK'),
(7, NULL, 2, 'Black', NULL, 'LOT-105', 'BAT-101', 5, 3000.0000, 3000.0000, 8, 0, 'Rib Collar - Received OK'),
(7, NULL, 3, 'Black', NULL, 'LOT-106', 'BAT-102', 1, 5000.0000, 5000.0000, 12, 0, 'Sewing Thread - Received OK');

-- ========================================
-- 3. ASN DOCUMENTS
-- ========================================

-- ASN-2026-0003 (In Transit)
INSERT IGNORE INTO asn_documents (asn_id, file_name, file_path, file_type, file_size, category, uploaded_by) VALUES
(5, 'INV-2026-567.pdf', '/uploads/asn-documents/INV-2026-567.pdf', 'application/pdf', 245000, 'commercial_invoice', 1),
(5, 'PL-2026-567.pdf', '/uploads/asn-documents/PL-2026-567.pdf', 'application/pdf', 128000, 'packing_list', 1),
(5, 'CH-2026-0654.pdf', '/uploads/asn-documents/CH-2026-0654.pdf', 'application/pdf', 89000, 'transport_lr', 1),
(5, 'QC-2026-101.pdf', '/uploads/asn-documents/QC-2026-101.pdf', 'application/pdf', 312000, 'test_certificate', 1);

-- ASN-2026-0004 (Arrived)
INSERT IGNORE INTO asn_documents (asn_id, file_name, file_path, file_type, file_size, category, uploaded_by) VALUES
(6, 'INV-2026-234.pdf', '/uploads/asn-documents/INV-2026-234.pdf', 'application/pdf', 267000, 'commercial_invoice', 1),
(6, 'PL-2026-234.pdf', '/uploads/asn-documents/PL-2026-234.pdf', 'application/pdf', 145000, 'packing_list', 1),
(6, 'CH-2026-0321.pdf', '/uploads/asn-documents/CH-2026-0321.pdf', 'application/pdf', 92000, 'transport_lr', 1),
(6, 'QC-2026-050.pdf', '/uploads/asn-documents/QC-2026-050.pdf', 'application/pdf', 298000, 'test_certificate', 1),
(6, 'CERT-2026-012.pdf', '/uploads/asn-documents/CERT-2026-012.pdf', 'application/pdf', 185000, 'certificate_of_origin', 1);

-- ASN-2026-0005 (Received)
INSERT IGNORE INTO asn_documents (asn_id, file_name, file_path, file_type, file_size, category, uploaded_by) VALUES
(7, 'INV-2026-101.pdf', '/uploads/asn-documents/INV-2026-101.pdf', 'application/pdf', 234000, 'commercial_invoice', 1),
(7, 'PL-2026-101.pdf', '/uploads/asn-documents/PL-2026-101.pdf', 'application/pdf', 156000, 'packing_list', 1),
(7, 'CH-2026-0100.pdf', '/uploads/asn-documents/CH-2026-0100.pdf', 'application/pdf', 78000, 'transport_lr', 1),
(7, 'QC-2026-020.pdf', '/uploads/asn-documents/QC-2026-020.pdf', 'application/pdf', 342000, 'test_certificate', 1),
(7, 'CERT-2026-008.pdf', '/uploads/asn-documents/CERT-2026-008.pdf', 'application/pdf', 175000, 'certificate_of_origin', 1);

-- ========================================
-- 4. ASN GATE ENTRIES
-- ========================================

-- ASN-2026-0004 (Arrived)
INSERT IGNORE INTO asn_gate_entry (asn_id, company_id, gate_entry_no, entry_time,
  vehicle_verified, seal_verified, documents_verified, invoice_verified, packing_list_verified,
  po_matched, quantity_verified,
  truck_photo, driver_photo, container_photo, seal_photo,
  gate_by, security_by, warehouse_by, notes, status) VALUES
(6, 1, 'GE-2026-0002', '2026-07-18 10:15:00',
  1, 1, 1, 1, 1, 1, 1,
  '/uploads/gate-photos/GE2-truck.jpg', '/uploads/gate-photos/GE2-driver.jpg', '/uploads/gate-photos/GE2-container.jpg', '/uploads/gate-photos/GE2-seal.jpg',
  1, 1, 1, 'All checks passed. Container seal intact. Driver ID verified.', 'completed');

-- ASN-2026-0005 (Received)
INSERT IGNORE INTO asn_gate_entry (asn_id, company_id, gate_entry_no, entry_time,
  vehicle_verified, seal_verified, documents_verified, invoice_verified, packing_list_verified,
  po_matched, quantity_verified,
  truck_photo, driver_photo, container_photo, seal_photo,
  gate_by, security_by, warehouse_by, notes, status) VALUES
(7, 1, 'GE-2026-0003', '2026-07-13 09:00:00',
  1, 1, 1, 1, 1, 1, 1,
  '/uploads/gate-photos/GE3-truck.jpg', '/uploads/gate-photos/GE3-driver.jpg', '/uploads/gate-photos/GE3-container.jpg', '/uploads/gate-photos/GE3-seal.jpg',
  1, 1, 1, 'Full container. All documentation verified. Driver released.', 'completed');

-- ========================================
-- 5. ASN TIMELINE EVENTS
-- ========================================

-- ASN-2026-0003 (In Transit)
INSERT IGNORE INTO asn_timeline (asn_id, event_type, event_label, event_details, performed_by, event_at) VALUES
(5, 'created', 'ASN ASN-2026-0003 created', '{"po_id":1,"supplier_id":2}', 1, '2026-07-17 09:00:00'),
(5, 'shipped', 'Shipment picked up from Mumbai warehouse', '{"vehicle":"DL01AB1234","driver":"Rajesh Kumar"}', 1, '2026-07-18 10:00:00'),
(5, 'in_transit', 'Shipment departed Mumbai distribution center', '{"location":"Mumbai, MH"}', 1, '2026-07-18 14:00:00'),
(5, 'in_transit', 'Shipment crossed Nagpur checkpoint', '{"location":"Nagpur, MH","eta_update":"Jul 22 2pm"}', 1, '2026-07-19 22:00:00'),
(5, 'in_transit', 'Shipment at Raipur rest stop', '{"location":"Raipur, CG","eta_update":"Jul 22 3pm"}', 1, '2026-07-20 18:00:00');

-- ASN-2026-0004 (Arrived)
INSERT IGNORE INTO asn_timeline (asn_id, event_type, event_label, event_details, performed_by, event_at) VALUES
(6, 'created', 'ASN ASN-2026-0004 created', '{"po_id":1,"supplier_id":5}', 1, '2026-07-14 09:00:00'),
(6, 'shipped', 'Shipment picked up from Gujarat warehouse', '{"vehicle":"GJ05CD7890","driver":"Mohammad Ali"}', 1, '2026-07-15 06:00:00'),
(6, 'in_transit', 'Shipment departed Ahmedabad', '{"location":"Ahmedabad, GJ"}', 1, '2026-07-15 10:00:00'),
(6, 'arrived', 'Shipment arrived at warehouse Dock-2', '{"arrival_time":"2026-07-18 09:30:00"}', 1, '2026-07-18 09:30:00'),
(6, 'gate_entry', 'Gate entry GE-2026-0002 completed - all checks passed', '{"vehicle":1,"seal":1,"documents":1,"po_match":1,"qty":1}', 1, '2026-07-18 10:15:00'),
(6, 'ai_analysis', 'AI analysis: 92% readiness - Excellent', '{"readiness_score":92,"recommendation":"Proceed with Standard Protocol"}', 1, '2026-07-18 10:16:00');

-- ASN-2026-0005 (Received)
INSERT IGNORE INTO asn_timeline (asn_id, event_type, event_label, event_details, performed_by, event_at) VALUES
(7, 'created', 'ASN ASN-2026-0005 created', '{"po_id":2,"supplier_id":1}', 1, '2026-07-09 10:00:00'),
(7, 'shipped', 'Shipment picked up from Bangalore warehouse', '{"vehicle":"KA01EF5678","driver":"Sunil Sharma"}', 1, '2026-07-10 06:00:00'),
(7, 'in_transit', 'Shipment departed Bangalore', '{"location":"Bangalore, KA"}', 1, '2026-07-10 10:00:00'),
(7, 'arrived', 'Shipment arrived at warehouse Dock-1', '{"arrival_time":"2026-07-13 08:00:00"}', 1, '2026-07-13 08:00:00'),
(7, 'gate_entry', 'Gate entry GE-2026-0003 completed - all checks passed', '{"vehicle":1,"seal":1,"documents":1,"po_match":1,"qty":1}', 1, '2026-07-13 09:00:00'),
(7, 'ai_analysis', 'AI analysis: 95% readiness - Excellent', '{"readiness_score":95,"recommendation":"Proceed with Standard Protocol"}', 1, '2026-07-13 09:05:00'),
(7, 'grn_created', 'GRN GRN-2026-0002 created from ASN', '{"grn_id":2}', 1, '2026-07-13 10:00:00'),
(7, 'received', 'All items verified and put away to warehouse', '{"warehouse_id":3,"items_received":6}', 1, '2026-07-13 14:00:00');

-- ========================================
-- 6. GRN #2 (from ASN-2026-0005)
-- ========================================
INSERT IGNORE INTO grn (id, company_id, grn_no, po_id, supplier_id, warehouse_id, received_by,
  received_date, invoice_no, invoice_date, vehicle_no, challan_no,
  total_qty, qc_status, status, notes) VALUES
(2, 1, 'GRN-2026-0002', 2, 1, 3, 1,
  '2026-07-13', 'INV-2026-101', '2026-07-10', 'KA01EF5678', 'CH-2026-0100',
  16000.0000, 'passed', 'qc_passed', 'GRN from ASN-2026-0005. All items QC passed.');

-- ========================================
-- 7. GRN ITEMS (for GRN-2)
-- ========================================
INSERT IGNORE INTO grn_items (grn_id, po_item_id, item_id, color, size, lot_no, batch_no, uom_id,
  received_qty, accepted_qty, rejected_qty, location_id, qc_status, notes) VALUES
(2, NULL, 1, 'Black', 'S', 'LOT-101', 'BAT-100', 5, 2000.0000, 2000.0000, 0, 1, 'passed', 'Size S - Accepted'),
(2, NULL, 1, 'Black', 'M', 'LOT-102', 'BAT-100', 5, 2000.0000, 2000.0000, 0, 1, 'passed', 'Size M - Accepted'),
(2, NULL, 1, 'Black', 'L', 'LOT-103', 'BAT-100', 5, 2000.0000, 2000.0000, 0, 1, 'passed', 'Size L - Accepted'),
(2, NULL, 1, 'Black', 'XL', 'LOT-104', 'BAT-100', 5, 2000.0000, 1980.0000, 20, 1, 'passed', 'Size XL - 20 pcs rejected (stain)'),
(2, NULL, 2, 'Black', NULL, 'LOT-105', 'BAT-101', 5, 3000.0000, 3000.0000, 0, 1, 'passed', 'Rib collar - All accepted'),
(2, NULL, 3, 'Black', NULL, 'LOT-106', 'BAT-102', 1, 5000.0000, 5000.0000, 0, 1, 'passed', 'Thread - All accepted');

-- ========================================
-- 8. VENDOR SCORECARDS (all 7 suppliers)
-- ========================================

DELETE FROM vendor_scorecards WHERE company_id = 1;

-- Supplier 1 — Fabric supplier (best performer)
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 1, '2026-01-01', '2026-06-30',
  12, 11, 95.50, 6,
  82.00, 98.00, 89.42, 'A', 'Top performer. Consistent quality and timely delivery.', 'active');

-- Supplier 2 — Trim supplier
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 2, '2026-01-01', '2026-06-30',
  8, 6, 92.00, 8,
  75.00, 85.00, 83.06, 'B', 'Good quality but occasional delays on bulk orders.', 'active');

-- Supplier 3 — Accessory supplier
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 3, '2026-01-01', '2026-06-30',
  15, 14, 97.00, 4,
  88.00, 95.00, 93.60, 'A', 'Excellent labels and accessories. Very responsive.', 'active');

-- Supplier 4 — Packaging supplier
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 4, '2026-01-01', '2026-06-30',
  6, 4, 85.00, 10,
  90.00, 70.00, 76.40, 'C', 'Competitive pricing but slow response times.', 'active');

-- Supplier 5 — Chemical supplier
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 5, '2026-01-01', '2026-06-30',
  10, 9, 93.00, 5,
  78.00, 90.00, 86.20, 'B', 'Reliable chemical supplier. Good technical support.', 'active');

-- Supplier 6 — Logistics provider
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 6, '2026-01-01', '2026-06-30',
  20, 18, 98.00, 3,
  72.00, 92.00, 88.40, 'A', 'Fastest logistics partner. GPS tracking available.', 'active');

-- Supplier 7 — New/poor performer
INSERT IGNORE INTO vendor_scorecards (company_id, supplier_id, period_start, period_end,
  total_orders, on_time_deliveries, quality_pass_rate, avg_lead_time_days,
  price_competitiveness, response_rate, overall_score, rating, notes, status) VALUES
(1, 7, '2026-01-01', '2026-06-30',
  3, 1, 70.00, 15,
  95.00, 50.00, 54.20, 'D', 'New supplier under probation. Quality issues detected.', 'active');

-- ========================================
-- 9. TNA PARTNERS (sample data)
-- ========================================
INSERT IGNORE INTO tna_partners (company_name, contact_name, email, password_hash, status, company_id) VALUES
('DyeChem Bangladesh', 'Kabir Rahman', 'kabir@dyechembd.com', '$2y$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ1234', 'active', 1),
('Label Masters Ltd', 'Nasrin Akter', 'nasrin@labelmasters.com', '$2y$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ1234', 'active', 1),
('PackWell Industries', 'Monir Hossain', 'monir@packwell.com', '$2y$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ1234', 'active', 1);

SELECT 'Seed data inserted successfully' as result;


-- ============================================================
-- FILE: migration_grn_enhanced.sql
-- ============================================================

-- ============================================================
-- MIGRATION: SAP-Style GRN (Goods Receipt Note) Sub-Tables
-- FashCognitive Digital GRN Module
-- ============================================================

-- ========================================
-- 1. ENHANCE grn TABLE — Add new columns
-- ========================================

ALTER TABLE `grn`
  ADD COLUMN `asn_id` int unsigned NULL AFTER `po_id`,
  ADD COLUMN `gate_entry_no` varchar(50) NULL AFTER `challan_no`,
  ADD COLUMN `driver_name` varchar(255) NULL AFTER `vehicle_no`,
  ADD COLUMN `driver_mobile` varchar(50) NULL AFTER `driver_name`,
  ADD COLUMN `transporter_name` varchar(255) NULL AFTER `driver_mobile`,
  ADD COLUMN `shift` varchar(50) NULL DEFAULT NULL AFTER `received_by`,
  ADD COLUMN `total_weight_kg` decimal(14,2) NULL DEFAULT NULL AFTER `total_qty`,
  ADD COLUMN `total_volume_cbm` decimal(10,3) NULL DEFAULT NULL AFTER `total_weight_kg`,
  ADD COLUMN `total_cartons` int unsigned NULL DEFAULT NULL AFTER `total_volume_cbm`,
  ADD COLUMN `total_pallets` int unsigned NULL DEFAULT NULL AFTER `total_cartons`,
  ADD COLUMN `received_at` datetime NULL DEFAULT NULL AFTER `received_date`,
  ADD COLUMN `confirmed_by` int unsigned NULL DEFAULT NULL AFTER `received_by`,
  ADD COLUMN `confirmed_at` datetime NULL DEFAULT NULL,
  ADD COLUMN `po_no_ref` varchar(50) NULL AFTER `po_id`,
  ADD COLUMN `supplier_name_ref` varchar(255) NULL AFTER `supplier_id`,
  ADD COLUMN `buyer_name` varchar(255) NULL DEFAULT NULL,
  ADD COLUMN `season` varchar(50) NULL DEFAULT NULL,
  ADD COLUMN `currency` varchar(10) NULL DEFAULT 'USD',
  ADD COLUMN `delivery_terms` varchar(50) NULL DEFAULT NULL,
  ADD COLUMN `payment_terms` varchar(50) NULL DEFAULT NULL,
  ADD INDEX `idx_grn_asn_id` (`asn_id`);

-- ========================================
-- 2. ENHANCE grn_items TABLE — Add putaway + batch columns
-- ========================================

ALTER TABLE `grn_items`
  ADD COLUMN `ordered_qty` decimal(14,4) NULL DEFAULT NULL AFTER `uom_id`,
  ADD COLUMN `item_name_ref` varchar(255) NULL DEFAULT NULL AFTER `item_id`,
  ADD COLUMN `color_name` varchar(100) NULL DEFAULT NULL AFTER `color`,
  ADD COLUMN `rate` decimal(12,2) NULL DEFAULT NULL AFTER `uom_id`,
  ADD COLUMN `line_total` decimal(14,2) NULL DEFAULT NULL AFTER `rate`,
  ADD COLUMN `warehouse_id` int unsigned NULL DEFAULT NULL AFTER `location_id`,
  ADD COLUMN `rack` varchar(50) NULL DEFAULT NULL AFTER `warehouse_id`,
  ADD COLUMN `bin` varchar(50) NULL DEFAULT NULL AFTER `rack`,
  ADD COLUMN `putaway_status` enum('pending','allocated','put_away') NOT NULL DEFAULT 'pending' AFTER `bin`,
  ADD COLUMN `batch_number` varchar(100) NULL DEFAULT NULL AFTER `batch_no`,
  ADD COLUMN `mfg_date` date NULL DEFAULT NULL AFTER `batch_number`,
  ADD COLUMN `expiry_date_new` date NULL DEFAULT NULL AFTER `mfg_date`,
  ADD COLUMN `internal_lot` varchar(100) NULL DEFAULT NULL AFTER `expiry_date_new`,
  ADD COLUMN `barcode` varchar(100) NULL DEFAULT NULL AFTER `internal_lot`,
  ADD COLUMN `qr_code` varchar(255) NULL DEFAULT NULL AFTER `barcode`;

-- ========================================
-- 3. GRN BATCHES — Batch tracking per GRN line
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_batches` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NOT NULL,
  `batch_number` varchar(100) NOT NULL,
  `mfg_date` date NULL DEFAULT NULL,
  `expiry_date` date NULL DEFAULT NULL,
  `supplier_lot` varchar(100) NULL DEFAULT NULL,
  `internal_lot` varchar(100) NULL DEFAULT NULL,
  `quantity` decimal(14,4) NOT NULL DEFAULT 0,
  `uom_id` int unsigned NOT NULL,
  `status` enum('active','expired','consumed','quarantine') NOT NULL DEFAULT 'active',
  `notes` text NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_batches_grn_id` (`grn_id`),
  KEY `idx_grn_batches_grn_item_id` (`grn_item_id`),
  KEY `idx_grn_batches_batch_number` (`batch_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 4. GRN ROLLS — Individual fabric rolls
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_rolls` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NOT NULL,
  `roll_no` varchar(50) NOT NULL,
  `roll_barcode` varchar(100) NULL DEFAULT NULL,
  `length_meters` decimal(10,2) NULL DEFAULT NULL,
  `width_cm` decimal(8,2) NULL DEFAULT NULL,
  `weight_kg` decimal(10,2) NULL DEFAULT NULL,
  `gsm` decimal(8,2) NULL DEFAULT NULL,
  `shade_grade` varchar(20) NULL DEFAULT NULL,
  `defect_notes` text NULL DEFAULT NULL,
  `image_path` varchar(500) NULL DEFAULT NULL,
  `status` enum('received','inspected','passed','rejected','in_stock','consumed') NOT NULL DEFAULT 'received',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_rolls_grn_id` (`grn_id`),
  KEY `idx_grn_rolls_roll_barcode` (`roll_barcode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 5. GRN IMAGES — Photos captured during receiving
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_images` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NULL DEFAULT NULL,
  `category` enum('truck','container','seal','material','damaged','fabric_roll','barcode_label','gate_entry','other') NOT NULL DEFAULT 'other',
  `file_name` varchar(255) NOT NULL,
  `file_path` varchar(500) NOT NULL,
  `file_type` varchar(100) NULL DEFAULT NULL,
  `file_size` int unsigned NULL DEFAULT 0,
  `caption` varchar(255) NULL DEFAULT NULL,
  `uploaded_by` int unsigned NULL DEFAULT NULL,
  `uploaded_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_images_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 6. GRN QUALITY RESULTS — Detailed QC inspection per item
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_quality_results` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NOT NULL,
  `inspection_type` varchar(100) NOT NULL DEFAULT 'incoming',
  `inspector_name` varchar(255) NULL DEFAULT NULL,
  `inspection_date` datetime NULL DEFAULT NULL,
  `sample_size` decimal(14,4) NULL DEFAULT NULL,
  `passed_qty` decimal(14,4) NULL DEFAULT NULL,
  `rejected_qty` decimal(14,4) NULL DEFAULT NULL,
  `result` enum('pending','passed','conditional','failed') NOT NULL DEFAULT 'pending',
  `fabric_4point` varchar(20) NULL DEFAULT NULL,
  `shade_approval` varchar(20) NULL DEFAULT NULL,
  `gsm_test` varchar(20) NULL DEFAULT NULL,
  `width_check` varchar(20) NULL DEFAULT NULL,
  `shrinkage_test` varchar(20) NULL DEFAULT NULL,
  `lab_test` varchar(20) NULL DEFAULT NULL,
  `defects` json NULL DEFAULT NULL,
  `remarks` text NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_qr_grn_id` (`grn_id`),
  KEY `idx_grn_qr_grn_item_id` (`grn_item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 7. GRN REJECTIONS — Detailed rejection records
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_rejections` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NOT NULL,
  `rejection_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `rejection_type` varchar(100) NOT NULL DEFAULT 'quality',
  `defect_type` varchar(100) NULL DEFAULT NULL,
  `defect_description` text NULL DEFAULT NULL,
  `disposition` enum('return_to_supplier','scrap','rework','hold') NOT NULL DEFAULT 'return_to_supplier',
  `image_path` varchar(500) NULL DEFAULT NULL,
  `inspected_by` int unsigned NULL DEFAULT NULL,
  `inspected_at` datetime NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_rej_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 8. GRN PUTAWAY — Warehouse bin allocation
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_putaway` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `rack` varchar(50) NULL DEFAULT NULL,
  `bin` varchar(50) NULL DEFAULT NULL,
  `location_code` varchar(100) NULL DEFAULT NULL,
  `allocated_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `putaway_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `status` enum('suggested','allocated','put_away','confirmed') NOT NULL DEFAULT 'suggested',
  `putaway_by` int unsigned NULL DEFAULT NULL,
  `putaway_at` datetime NULL DEFAULT NULL,
  `notes` text NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_putaway_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 9. GRN BARCODES — Generated barcodes
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_barcodes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NULL DEFAULT NULL,
  `barcode_type` enum('barcode','qr_code') NOT NULL DEFAULT 'barcode',
  `barcode_value` varchar(255) NOT NULL,
  `barcode_image_path` varchar(500) NULL DEFAULT NULL,
  `label_text` varchar(255) NULL DEFAULT NULL,
  `generated_by` int unsigned NULL DEFAULT NULL,
  `generated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_barcodes_grn_id` (`grn_id`),
  KEY `idx_grn_barcodes_value` (`barcode_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 10. GRN APPROVALS — Multi-level approval workflow
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_approvals` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `approval_level` int unsigned NOT NULL DEFAULT 1,
  `role_required` varchar(100) NOT NULL DEFAULT 'warehouse_manager',
  `approver_name` varchar(255) NULL DEFAULT NULL,
  `approver_id` int unsigned NULL DEFAULT NULL,
  `status` enum('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `comments` text NULL DEFAULT NULL,
  `approved_at` datetime NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_approvals_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 11. GRN AI ANALYSIS — AI inspection results
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_ai_analysis` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NULL DEFAULT NULL,
  `analysis_type` varchar(100) NOT NULL DEFAULT 'fabric_inspection',
  `readiness_score` decimal(5,2) NULL DEFAULT NULL,
  `shade_variation` varchar(20) NULL DEFAULT NULL,
  `width_variation_pct` decimal(6,2) NULL DEFAULT NULL,
  `moisture_level` varchar(50) NULL DEFAULT NULL,
  `defect_density` varchar(20) NULL DEFAULT NULL,
  `predicted_grade` varchar(10) NULL DEFAULT NULL,
  `ai_recommendation` varchar(255) NULL DEFAULT NULL,
  `ai_raw_data` json NULL DEFAULT NULL,
  `analyzed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_ai_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 12. GRN INVENTORY TRANSACTIONS — Stock impact log
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_inventory_transactions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `grn_item_id` int unsigned NOT NULL,
  `warehouse_id` int unsigned NOT NULL,
  `item_id` int unsigned NOT NULL,
  `color` varchar(100) NULL DEFAULT NULL,
  `size` varchar(100) NULL DEFAULT NULL,
  `lot_no` varchar(100) NULL DEFAULT NULL,
  `batch_number` varchar(100) NULL DEFAULT NULL,
  `uom_id` int unsigned NOT NULL,
  `qty_before` decimal(14,4) NOT NULL DEFAULT 0,
  `qty_received` decimal(14,4) NOT NULL DEFAULT 0,
  `qty_after` decimal(14,4) NOT NULL DEFAULT 0,
  `unit_cost` decimal(12,2) NULL DEFAULT NULL,
  `total_cost` decimal(14,2) NULL DEFAULT NULL,
  `movement_type` varchar(50) NOT NULL DEFAULT 'purchase_in',
  `reference_type` varchar(50) NOT NULL DEFAULT 'grn',
  `reference_id` int unsigned NOT NULL,
  `notes` text NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_invtx_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ========================================
-- 13. GRN APPROVAL SIGNATURES (digital)
-- ========================================

CREATE TABLE IF NOT EXISTS `grn_approval_signatures` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `grn_id` int unsigned NOT NULL,
  `approval_id` int unsigned NOT NULL,
  `signer_name` varchar(255) NOT NULL,
  `signer_role` varchar(100) NOT NULL,
  `signature_data` text NULL DEFAULT NULL,
  `signed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_grn_sigs_grn_id` (`grn_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

SELECT 'GRN migration completed successfully' as result;


-- ============================================================
-- FILE: seed_grn_enhanced.sql
-- ============================================================

-- ============================================================
-- SEED DATA: Enhanced GRN Sub-Table Records
-- ============================================================

-- Update existing GRNs with enhanced fields
UPDATE grn SET
  asn_id = 7, po_no_ref = 'PO-2026-0001', supplier_name_ref = 'Textile Mills India',
  driver_name = 'Sunil Sharma', driver_mobile = '+919876543213', transporter_name = 'National Logistics',
  gate_entry_no = 'GE-2026-0003', shift = 'Morning', total_weight_kg = 9800.00, total_volume_cbm = 32.000,
  total_cartons = 40, total_pallets = 3, buyer_name = 'Nike', season = 'SS2026', currency = 'USD',
  delivery_terms = 'FOB', payment_terms = '60 Days', received_at = '2026-07-13 09:00:00'
WHERE id = 2;

UPDATE grn SET
  po_no_ref = 'PO-2026-0002', supplier_name_ref = 'Fashion Trims Co',
  driver_name = 'Kumar', driver_mobile = '+919876543210', transporter_name = 'FastCargo Logistics',
  gate_entry_no = 'GE-2026-0001', shift = 'Morning', total_weight_kg = 1035.00, total_volume_cbm = 6.900,
  total_cartons = 30, total_pallets = 0, buyer_name = 'Zara', season = 'AW2026', currency = 'USD',
  delivery_terms = 'CIF', payment_terms = '45 Days', received_at = '2026-07-20 11:30:00'
WHERE id = 1;

-- ========================================
-- 1. GRN BATCHES — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_batches (grn_id, grn_item_id, batch_number, mfg_date, expiry_date, supplier_lot, internal_lot, quantity, uom_id, status, notes) VALUES
(2, 3, 'BATCH-2026-0713-001', '2026-07-01', NULL, 'LOT-101', 'FC-LOT-001', 2000.0000, 5, 'active', 'Cotton Jersey Size S'),
(2, 4, 'BATCH-2026-0713-002', '2026-07-01', NULL, 'LOT-102', 'FC-LOT-002', 2000.0000, 5, 'active', 'Cotton Jersey Size M'),
(2, 5, 'BATCH-2026-0713-003', '2026-07-01', NULL, 'LOT-103', 'FC-LOT-003', 2000.0000, 5, 'active', 'Cotton Jersey Size L'),
(2, 6, 'BATCH-2026-0713-004', '2026-07-01', NULL, 'LOT-104', 'FC-LOT-004', 1980.0000, 5, 'active', 'Cotton Jersey Size XL (20 rejected)'),
(2, 7, 'BATCH-2026-0713-005', '2026-06-28', NULL, 'LOT-105', 'FC-LOT-005', 3000.0000, 5, 'active', 'Rib Collar'),
(2, 8, 'BATCH-2026-0713-006', '2026-07-05', NULL, 'LOT-106', 'FC-LOT-006', 5000.0000, 1, 'active', 'Sewing Thread');

-- ========================================
-- 2. GRN ROLLS — For GRN-2 (fabric rolls)
-- ========================================
INSERT IGNORE INTO grn_rolls (grn_id, grn_item_id, roll_no, roll_barcode, length_meters, width_cm, weight_kg, gsm, shade_grade, defect_notes, status) VALUES
(2, 3, 'R-001', 'RL-2026-0001', 58.50, 180.00, 52.65, 178.00, 'A', NULL, 'passed'),
(2, 3, 'R-002', 'RL-2026-0002', 62.00, 180.00, 55.80, 179.00, 'A', NULL, 'passed'),
(2, 3, 'R-003', 'RL-2026-0003', 55.00, 180.00, 49.50, 177.50, 'A', NULL, 'passed'),
(2, 3, 'R-004', 'RL-2026-0004', 60.00, 180.00, 54.00, 178.00, 'A', 'Minor shade variation at edge', 'passed'),
(2, 4, 'R-005', 'RL-2026-0005', 58.00, 180.00, 52.20, 178.50, 'A', NULL, 'passed'),
(2, 4, 'R-006', 'RL-2026-0006', 61.00, 180.00, 54.90, 179.00, 'A', NULL, 'passed'),
(2, 4, 'R-007', 'RL-2026-0007', 57.50, 180.00, 51.75, 178.00, 'A', NULL, 'passed'),
(2, 4, 'R-008', 'RL-2026-0008', 60.50, 180.00, 54.45, 178.50, 'A', NULL, 'passed'),
(2, 5, 'R-009', 'RL-2026-0009', 59.00, 180.00, 53.10, 178.00, 'A', NULL, 'passed'),
(2, 5, 'R-010', 'RL-2026-0010', 61.50, 180.00, 55.35, 179.00, 'A', NULL, 'passed'),
(2, 5, 'R-011', 'RL-2026-0011', 56.00, 180.00, 50.40, 177.50, 'B', 'Slight curling at selvedge', 'passed'),
(2, 6, 'R-012', 'RL-2026-0012', 58.00, 180.00, 52.20, 178.00, 'A', NULL, 'passed');

-- ========================================
-- 3. GRN IMAGES — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_images (grn_id, category, file_name, file_path, file_type, file_size, caption, uploaded_by) VALUES
(2, 'truck', 'truck-arrival.jpg', '/uploads/grn-images/truck-arrival.jpg', 'image/jpeg', 2450000, 'Truck KA01EF5678 arriving at Dock-1', 1),
(2, 'container', 'container-seal.jpg', '/uploads/grn-images/container-seal.jpg', 'image/jpeg', 1890000, 'Container seal intact on arrival', 1),
(2, 'material', 'fabric-pallet-1.jpg', '/uploads/grn-images/fabric-pallet-1.jpg', 'image/jpeg', 3200000, 'First pallet of fabric rolls', 1),
(2, 'material', 'fabric-pallet-2.jpg', '/uploads/grn-images/fabric-pallet-2.jpg', 'image/jpeg', 2800000, 'Second pallet - rib collars', 1),
(2, 'fabric_roll', 'roll-inspection.jpg', '/uploads/grn-images/roll-inspection.jpg', 'image/jpeg', 1500000, 'Roll inspection at receiving dock', 1),
(2, 'barcode_label', 'grn-barcode.jpg', '/uploads/grn-images/grn-barcode.jpg', 'image/jpeg', 890000, 'GRN barcode label applied', 1);

-- ========================================
-- 4. GRN QUALITY RESULTS — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_quality_results (grn_id, grn_item_id, inspection_type, inspector_name, inspection_date, sample_size, passed_qty, rejected_qty, result, fabric_4point, shade_approval, gsm_test, width_check, shrinkage_test, lab_test, defects, remarks) VALUES
(2, 3, 'incoming', 'Fatima Begum', '2026-07-13 14:00:00', 200.0000, 198.0000, 2.0000, 'passed', 'Passed', 'Passed', 'Passed', 'Passed', 'Passed', 'Passed',
  '[{"defect":"Minor shade variation","count":2}]', 'Minor shade variation on 2 rolls. Within tolerance.'),
(2, 7, 'incoming', 'Fatima Begum', '2026-07-13 15:00:00', 500.0000, 500.0000, 0, 'passed', 'Passed', 'Passed', 'N/A', 'N/A', 'N/A', 'N/A', NULL, 'Rib collars passed all checks'),
(2, 8, 'incoming', 'Fatima Begum', '2026-07-13 15:30:00', 1000.0000, 1000.0000, 0, 'passed', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A', 'Passed', NULL, 'Thread tensile strength OK');

-- ========================================
-- 5. GRN REJECTIONS — For GRN-2 (from item 6 / XL)
-- ========================================
INSERT IGNORE INTO grn_rejections (grn_id, grn_item_id, rejection_qty, rejection_type, defect_type, defect_description, disposition, inspected_by, inspected_at) VALUES
(2, 6, 20.0000, 'quality', 'stain', 'Oil stains on 20 fabric pieces (Size XL). Likely from cutting machine.', 'return_to_supplier', 1, '2026-07-13 16:00:00');

-- ========================================
-- 6. GRN PUTAWAY — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_putaway (grn_id, grn_item_id, warehouse_id, rack, bin, location_code, allocated_qty, putaway_qty, status, putaway_by, putaway_at, notes) VALUES
(2, 3, 3, 'A', 'A-01', 'FC-FAB-001', 2000.0000, 2000.0000, 'put_away', 1, '2026-07-13 16:30:00', 'Size S fabric stored'),
(2, 4, 3, 'A', 'A-02', 'FC-FAB-002', 2000.0000, 2000.0000, 'put_away', 1, '2026-07-13 16:35:00', 'Size M fabric stored'),
(2, 5, 3, 'A', 'A-03', 'FC-FAB-003', 2000.0000, 2000.0000, 'put_away', 1, '2026-07-13 16:40:00', 'Size L fabric stored'),
(2, 6, 3, 'A', 'A-04', 'FC-FAB-004', 1980.0000, 1980.0000, 'put_away', 1, '2026-07-13 16:45:00', 'Size XL fabric stored (after QC)'),
(2, 7, 3, 'B', 'B-01', 'FC-TRM-001', 3000.0000, 3000.0000, 'put_away', 1, '2026-07-13 17:00:00', 'Rib collar stored in trim section'),
(2, 8, 3, 'B', 'B-02', 'FC-TRM-002', 5000.0000, 5000.0000, 'put_away', 1, '2026-07-13 17:05:00', 'Sewing thread stored');

-- ========================================
-- 7. GRN BARCODES — For GRN-1 and GRN-2
-- ========================================
INSERT IGNORE INTO grn_barcodes (grn_id, barcode_type, barcode_value, label_text, generated_by) VALUES
(2, 'barcode', 'GRN20260002', 'GRN: GRN-2026-0002', 1),
(2, 'qr_code', 'https://erp.fashcognitive.com/grn/GRN-2026-0002', 'QR: GRN-2026-0002', 1),
(1, 'barcode', 'GRN20260001', 'GRN: GRN-2026-0001', 1),
(1, 'qr_code', 'https://erp.fashcognitive.com/grn/GRN-2026-0001', 'QR: GRN-2026-0001', 1);

-- ========================================
-- 8. GRN APPROVALS — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_approvals (grn_id, approval_level, role_required, approver_name, approver_id, status, comments, approved_at) VALUES
(2, 1, 'warehouse_manager', 'Admin User', 1, 'approved', 'Goods verified at dock', '2026-07-13 17:10:00'),
(2, 2, 'quality_inspector', 'Fatima Begum', 1, 'approved', 'QC passed - all parameters within tolerance', '2026-07-13 17:15:00'),
(2, 3, 'purchase_manager', 'Admin User', 1, 'approved', 'Approved for inventory', '2026-07-13 17:20:00');

-- ========================================
-- 9. GRN AI ANALYSIS — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_ai_analysis (grn_id, grn_item_id, analysis_type, readiness_score, shade_variation, width_variation_pct, moisture_level, defect_density, predicted_grade, ai_recommendation, ai_raw_data) VALUES
(2, 3, 'fabric_inspection', 95.00, 'LOW', 0.25, 'Normal', 'LOW', 'A', 'Accept Material - Excellent Quality',
  '{"readiness_score":95,"shade_variation":"LOW","width_variation_pct":0.25,"moisture_level":"Normal","defect_density":"LOW","predicted_grade":"A","ai_recommendation":"Accept Material - Excellent Quality","fabric_images_analyzed":12,"defects_found":0,"confidence":0.96}'),
(2, 6, 'fabric_inspection', 72.00, 'MEDIUM', 1.20, 'Normal', 'MEDIUM', 'B', 'Conditional Accept - Manual Review Required',
  '{"readiness_score":72,"shade_variation":"MEDIUM","width_variation_pct":1.20,"moisture_level":"Normal","defect_density":"MEDIUM","predicted_grade":"B","ai_recommendation":"Conditional Accept - Manual Review Required","fabric_images_analyzed":8,"defects_found":2,"confidence":0.82}');

-- ========================================
-- 10. GRN INVENTORY TRANSACTIONS — For GRN-2
-- ========================================
INSERT IGNORE INTO grn_inventory_transactions (grn_id, grn_item_id, warehouse_id, item_id, color, size, lot_no, batch_number, uom_id, qty_before, qty_received, qty_after, unit_cost, total_cost, movement_type, reference_type, reference_id, notes) VALUES
(2, 3, 3, 1, 'Black', 'S', 'LOT-101', 'BATCH-2026-0713-001', 5, 0, 2000.0000, 2000.0000, 4.50, 9000.00, 'purchase_in', 'grn', 2, 'Size S fabric received'),
(2, 4, 3, 1, 'Black', 'M', 'LOT-102', 'BATCH-2026-0713-002', 5, 0, 2000.0000, 2000.0000, 4.50, 9000.00, 'purchase_in', 'grn', 2, 'Size M fabric received'),
(2, 5, 3, 1, 'Black', 'L', 'LOT-103', 'BATCH-2026-0713-003', 5, 0, 2000.0000, 2000.0000, 4.50, 9000.00, 'purchase_in', 'grn', 2, 'Size L fabric received'),
(2, 6, 3, 1, 'Black', 'XL', 'LOT-104', 'BATCH-2026-0713-004', 5, 0, 1980.0000, 1980.0000, 4.50, 8910.00, 'purchase_in', 'grn', 2, 'Size XL fabric received (20 rejected)'),
(2, 7, 3, 2, 'Black', NULL, 'LOT-105', 'BATCH-2026-0713-005', 5, 0, 3000.0000, 3000.0000, 8.00, 24000.00, 'purchase_in', 'grn', 2, 'Rib collar received'),
(2, 8, 3, 3, 'Black', NULL, 'LOT-106', 'BATCH-2026-0713-006', 1, 0, 5000.0000, 5000.0000, 0.10, 500.00, 'purchase_in', 'grn', 2, 'Sewing thread received');

SELECT 'GRN seed data inserted successfully' as result;


-- ============================================================
-- FILE: migration_supplier_portal.sql
-- ============================================================

CREATE TABLE IF NOT EXISTS `supplier_portal_invites` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `supplier_id` INT UNSIGNED NOT NULL,
  `company_id` INT UNSIGNED DEFAULT 1,
  `invited_by` INT UNSIGNED DEFAULT NULL,
  `token` VARCHAR(64) NOT NULL,
  `status` ENUM('pending','activated','submitted','expired') NOT NULL DEFAULT 'pending',
  `expires_at` DATETIME NOT NULL,
  `activated_at` DATETIME DEFAULT NULL,
  `submitted_at` DATETIME DEFAULT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_token` (`token`),
  KEY `idx_supplier` (`supplier_id`),
  CONSTRAINT `fk_invite_supplier` FOREIGN KEY (`supplier_id`) REFERENCES `supplier_profiles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `supplier_portal_submissions` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `invite_id` INT UNSIGNED NOT NULL,
  `supplier_id` INT UNSIGNED NOT NULL,
  `company_name` VARCHAR(255) DEFAULT NULL,
  `factory_name` VARCHAR(255) DEFAULT NULL,
  `factory_address` TEXT DEFAULT NULL,
  `city` VARCHAR(100) DEFAULT NULL,
  `state` VARCHAR(100) DEFAULT NULL,
  `country` VARCHAR(100) DEFAULT NULL,
  `postal_code` VARCHAR(20) DEFAULT NULL,
  `latitude` DECIMAL(10,7) DEFAULT NULL,
  `longitude` DECIMAL(10,7) DEFAULT NULL,
  `contact_person` VARCHAR(255) DEFAULT NULL,
  `contact_email` VARCHAR(255) DEFAULT NULL,
  `contact_phone` VARCHAR(50) DEFAULT NULL,
  `contact_designation` VARCHAR(100) DEFAULT NULL,
  `year_established` YEAR DEFAULT NULL,
  `facility_size_sqft` INT UNSIGNED DEFAULT NULL,
  `total_employees` INT UNSIGNED DEFAULT NULL,
  `annual_revenue_usd` DECIMAL(15,2) DEFAULT NULL,
  `num_sewing_lines` INT UNSIGNED DEFAULT NULL,
  `num_cutting_tables` INT UNSIGNED DEFAULT NULL,
  `num_finishing_lines` INT UNSIGNED DEFAULT NULL,
  `monthly_capacity` INT UNSIGNED DEFAULT NULL,
  `capacity_utilization` DECIMAL(5,2) DEFAULT NULL,
  `lead_time_days` INT UNSIGNED DEFAULT NULL,
  `machinery_details` JSON DEFAULT NULL,
  `departments` JSON DEFAULT NULL,
  `compliance_details` JSON DEFAULT NULL,
  `environmental_details` JSON DEFAULT NULL,
  `chemical_management` JSON DEFAULT NULL,
  `warehouse_details` JSON DEFAULT NULL,
  `progress_pct` INT UNSIGNED NOT NULL DEFAULT 0,
  `status` ENUM('draft','submitted','under_review','approved','rejected') NOT NULL DEFAULT 'draft',
  `reviewer_notes` TEXT DEFAULT NULL,
  `reviewed_by` INT UNSIGNED DEFAULT NULL,
  `reviewed_at` DATETIME 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`),
  KEY `idx_invite` (`invite_id`),
  KEY `idx_supplier` (`supplier_id`),
  CONSTRAINT `fk_sub_invite` FOREIGN KEY (`invite_id`) REFERENCES `supplier_portal_invites` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_sub_supplier` FOREIGN KEY (`supplier_id`) REFERENCES `supplier_profiles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `supplier_portal_documents` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `submission_id` INT UNSIGNED NOT NULL,
  `doc_category` ENUM('iso_9001','iso_14001','wrap','bsci','sedex','sa8000','oeko_tex','gots','grs','higg','zdhc','fire_certificate','building_license','factory_license','insurance','calibration','environmental_report','msds','training_records','payroll','other') NOT NULL DEFAULT 'other',
  `doc_name` VARCHAR(255) NOT NULL,
  `file_name` VARCHAR(255) NOT NULL,
  `file_path` VARCHAR(500) NOT NULL,
  `file_size` INT UNSIGNED DEFAULT NULL,
  `mime_type` VARCHAR(100) DEFAULT NULL,
  `expiry_date` DATE DEFAULT NULL,
  `is_expired` TINYINT(1) NOT NULL DEFAULT 0,
  `ai_status` ENUM('pending','valid','expiring_soon','expired','unreadable','wrong_file') NOT NULL DEFAULT 'pending',
  `ai_notes` TEXT DEFAULT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_submission` (`submission_id`),
  CONSTRAINT `fk_doc_submission` FOREIGN KEY (`submission_id`) REFERENCES `supplier_portal_submissions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `supplier_portal_photos` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `submission_id` INT UNSIGNED NOT NULL,
  `photo_category` ENUM('factory_entrance','production_floor','warehouse','chemical_room','fire_safety','dormitory','canteen','packing','loading_area','office','laboratory','waste_area','solar','other') NOT NULL DEFAULT 'other',
  `file_name` VARCHAR(255) NOT NULL,
  `file_path` VARCHAR(500) NOT NULL,
  `file_size` INT UNSIGNED DEFAULT NULL,
  `mime_type` VARCHAR(100) DEFAULT NULL,
  `caption` VARCHAR(255) DEFAULT NULL,
  `gps_lat` DECIMAL(10,7) DEFAULT NULL,
  `gps_lng` DECIMAL(10,7) DEFAULT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_submission` (`submission_id`),
  CONSTRAINT `fk_photo_submission` FOREIGN KEY (`submission_id`) REFERENCES `supplier_portal_submissions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: migration_supplier_capa_portal.sql
-- ============================================================

-- Supplier CAPA Portal Migration
-- Adds tables for supplier-facing CAPA response workflow

-- Evidence files uploaded by suppliers in response to CAPAs
CREATE TABLE IF NOT EXISTS supplier_capa_evidence (
    id INT AUTO_INCREMENT PRIMARY KEY,
    capa_id INT UNSIGNED NOT NULL,
    supplier_id INT NOT NULL,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size INT DEFAULT NULL,
    mime_type VARCHAR(100) DEFAULT NULL,
    evidence_type ENUM('root_cause', 'corrective_action', 'preventive_action', 'general') DEFAULT 'general',
    description TEXT DEFAULT NULL,
    uploaded_by VARCHAR(100) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_capa_id (capa_id),
    INDEX idx_supplier_id (supplier_id),
    FOREIGN KEY (capa_id) REFERENCES supplier_audit_capa(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Track portal CAPA acknowledgements and response timeline
CREATE TABLE IF NOT EXISTS supplier_capa_timeline (
    id INT AUTO_INCREMENT PRIMARY KEY,
    capa_id INT UNSIGNED NOT NULL,
    action_type ENUM('viewed', 'acknowledged', 'responded', 'evidence_uploaded', 'status_change') NOT NULL,
    action_by VARCHAR(100) DEFAULT NULL,
    action_notes TEXT DEFAULT NULL,
    old_status VARCHAR(50) DEFAULT NULL,
    new_status VARCHAR(50) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_capa_id (capa_id),
    FOREIGN KEY (capa_id) REFERENCES supplier_audit_capa(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ============================================================
-- FILE: migration_supplier_portal_v2.sql
-- ============================================================

-- Add missing columns to supplier_portal_submissions
-- Uses procedure to safely add columns only if they don't exist

DELIMITER //
CREATE PROCEDURE add_portal_v2_columns()
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'current_step') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN current_step INT UNSIGNED DEFAULT 0 AFTER progress_pct;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'supplier_type') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN supplier_type ENUM('fabric','trim','accessory','chemical','packaging','cmt','full_package','service','other') DEFAULT 'fabric' AFTER notes;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'country_code') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN country_code VARCHAR(10) DEFAULT NULL AFTER country;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'last_accessed_at') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN last_accessed_at TIMESTAMP NULL DEFAULT NULL AFTER updated_at;
    END IF;
END //
DELIMITER ;

CALL add_portal_v2_columns();
DROP PROCEDURE add_portal_v2_columns;


-- ============================================================
-- FILE: migration_supplier_portal_v2b.sql
-- ============================================================

-- Add remaining missing columns
DELIMITER //
CREATE PROCEDURE add_portal_v2b_columns()
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'supplier_type') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN supplier_type ENUM('fabric','trim','accessory','chemical','packaging','cmt','full_package','service','other') DEFAULT 'fabric' AFTER warehouse_details;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'notes') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN notes TEXT DEFAULT NULL AFTER supplier_type;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'supplier_portal_submissions' AND column_name = 'last_accessed_at') THEN
        ALTER TABLE supplier_portal_submissions ADD COLUMN last_accessed_at TIMESTAMP NULL DEFAULT NULL AFTER updated_at;
    END IF;
END //
DELIMITER ;

CALL add_portal_v2b_columns();
DROP PROCEDURE add_portal_v2b_columns;


-- ============================================================
-- FILE: migration_supplier_portal_v3.sql
-- ============================================================

-- Migration: Supplier Portal v3 — Password Reset Support
-- Adds reset_token and reset_token_expires columns to supplier_portal_users

ALTER TABLE supplier_portal_users
  ADD COLUMN reset_token VARCHAR(128) DEFAULT NULL,
  ADD COLUMN reset_token_expires DATETIME DEFAULT NULL;

CREATE INDEX idx_supplier_portal_users_reset_token ON supplier_portal_users(reset_token);


-- ============================================================
-- FILE: seed_supplier_audit.sql
-- ============================================================

-- ============================================================
-- Supplier Audit Module — Comprehensive Seed Data
-- Run: mysql -u root fcqc_database < database/seed_supplier_audit.sql
-- ============================================================

SET @company_id = 1;

-- ============================================================
-- 1. SUPPLIER PROFILES (add 20 more diverse suppliers)
-- ============================================================
INSERT IGNORE INTO supplier_profiles (
    company_id, supplier_name, supplier_code, factory_name, country, city,
    supplier_type, contact_person, contact_email, contact_phone,
    audit_status, overall_score, risk_level, last_audit_date,
    year_established, facility_size_sqft, total_employees,
    num_sewing_lines, monthly_capacity, lead_time_days,
    latitude, longitude, status, created_at
) VALUES
(@company_id, 'Apex Textile Mills', 'SUP-017', 'Apex Factory Unit 1', 'Bangladesh', 'Dhaka', 'fabric', 'Rahman Khan', 'rahman@apextextile.com', '+880-171-555-0101', 'approved', 87.50, 'low', '2025-11-15', 2005, 45000, 320, 12, 50000, 45, 23.8103, 90.4125, 'active', NOW()),
(@company_id, 'Star Garments Ltd', 'SUP-018', 'Star Unit A', 'Bangladesh', 'Chittagong', 'cmt', 'Fatima Ahmed', 'fatima@stargarments.com', '+880-181-555-0202', 'approved', 92.10, 'low', '2025-10-20', 2008, 62000, 480, 18, 80000, 40, 22.3569, 91.7832, 'active', NOW()),
(@company_id, 'Delta Knitwears', 'SUP-019', 'Delta Knitting Unit', 'Bangladesh', 'Gazipur', 'full_package', 'Karim Hassan', 'karim@deltaknit.com', '+880-191-555-0303', 'conditional', 68.20, 'medium', '2025-09-10', 2001, 35000, 250, 8, 35000, 50, 23.9999, 90.4075, 'active', NOW()),
(@company_id, 'Bombay Synthetics', 'SUP-020', 'Bombay Mill 3', 'India', 'Mumbai', 'fabric', 'Priya Sharma', 'priya@bombaysynth.in', '+91-98765-43210', 'approved', 91.30, 'low', '2025-12-01', 1998, 80000, 600, 24, 120000, 35, 19.0760, 72.8777, 'active', NOW()),
(@company_id, 'Chennai Exports Pvt', 'SUP-021', 'Chennai Factory Block B', 'India', 'Chennai', 'full_package', 'Anand Raj', 'anand@chennaiexports.in', '+91-98765-54321', 'approved', 84.60, 'low', '2025-08-25', 2010, 55000, 400, 16, 70000, 38, 13.0827, 80.2707, 'active', NOW()),
(@company_id, 'Tirupur Textiles', 'SUP-022', 'Tirupur Processing Unit', 'India', 'Tirupur', 'fabric', 'Meena Devi', 'meena@tirupurtex.in', '+91-98765-65432', 'blocked', 45.80, 'critical', '2025-06-15', 1995, 30000, 180, 6, 25000, 55, 11.1085, 77.3411, 'active', NOW()),
(@company_id, 'Saigon Fashion Co', 'SUP-023', 'SGN Workshop 2', 'Vietnam', 'Ho Chi Minh City', 'cmt', 'Nguyen Van Thanh', 'thanhn@saigonfashion.vn', '+84-901-234-567', 'approved', 89.70, 'low', '2025-11-05', 2012, 42000, 350, 14, 60000, 42, 10.8231, 106.6297, 'active', NOW()),
(@company_id, 'Hanoi Garment JSC', 'SUP-024', 'HN Garment Factory', 'Vietnam', 'Hanoi', 'full_package', 'Tran Thi Mai', 'mai@hanoigarment.vn', '+84-912-345-678', 'conditional', 71.50, 'medium', '2025-07-20', 2006, 50000, 380, 15, 65000, 48, 21.0278, 105.8342, 'active', NOW()),
(@company_id, 'Istanbul Tekstil', 'SUP-025', 'Istanbul Main Factory', 'Turkey', 'Istanbul', 'fabric', 'Mehmet Ozkan', 'mehmet@istanbultekstil.com.tr', '+90-532-123-4567', 'approved', 93.40, 'low', '2025-12-10', 2000, 70000, 520, 20, 90000, 30, 41.0082, 28.9784, 'active', NOW()),
(@company_id, 'Anadolu Giyim', 'SUP-026', 'Anadolu Workshop', 'Turkey', 'Bursa', 'trim', 'Elif Yilmaz', 'elif@anadolugiyim.com.tr', '+90-532-987-6543', 'approved', 86.90, 'low', '2025-10-01', 2015, 25000, 180, 0, 0, 28, 40.1826, 29.0665, 'active', NOW()),
(@company_id, 'Shenzhen Smart Textiles', 'SUP-027', 'SZ Smart Factory', 'China', 'Shenzhen', 'full_package', 'Wei Zhang', 'wei@shenzhensmart.cn', '+86-138-1234-5678', 'approved', 95.20, 'low', '2025-12-15', 2003, 95000, 750, 30, 150000, 25, 22.5431, 114.0579, 'active', NOW()),
(@company_id, 'Guangzhou Fashion Hub', 'SUP-028', 'GZH Unit 1', 'China', 'Guangzhou', 'cmt', 'Liu Wei', 'liu@gzfashion.cn', '+86-139-8765-4321', 'conditional', 65.30, 'high', '2025-05-10', 2009, 38000, 280, 10, 45000, 52, 23.1291, 113.2644, 'active', NOW()),
(@company_id, 'Colombo Clothing Co', 'SUP-029', 'Colombo SEZ Factory', 'Sri Lanka', 'Colombo', 'full_package', 'Sunil Perera', 'sunil@colomboclothing.lk', '+94-77-123-4567', 'approved', 88.40, 'low', '2025-09-30', 2007, 48000, 360, 14, 55000, 44, 6.9271, 79.8612, 'active', NOW()),
(@company_id, 'Lahore Textile Mills', 'SUP-030', 'LTM Weaving Unit', 'Pakistan', 'Lahore', 'fabric', 'Ahmed Raza', 'ahmed@lahoretextile.pk', '+92-321-1234567', 'pending_qualification', 0, 'medium', NULL, 2011, 40000, 290, 10, 40000, 48, 31.5204, 74.3587, 'active', NOW()),
(@company_id, 'Phnom Penh Garment', 'SUP-031', 'PPG Factory', 'Cambodia', 'Phnom Penh', 'cmt', 'Dara Sok', 'dara@phnompenhgarment.kh', '+855-12-345-6789', 'approved', 82.10, 'low', '2025-08-15', 2014, 32000, 240, 10, 40000, 46, 11.5564, 104.9282, 'active', NOW()),
(@company_id, 'Bandung Textile Pro', 'SUP-032', 'BTP Factory', 'Indonesia', 'Bandung', 'fabric', 'Rudi Hartono', 'rudi@bandungtextile.co.id', '+62-812-3456-7890', 'approved', 80.50, 'medium', '2025-07-01', 2002, 58000, 420, 16, 75000, 42, -6.9175, 107.6191, 'active', NOW()),
(@company_id, 'Yangon Fashion Ltd', 'SUP-033', 'YFL Workshop', 'Myanmar', 'Yangon', 'cmt', 'Aung Kyaw', 'aung@yangonfashion.mm', '+95-9-1234-5678', 'blocked', 38.20, 'critical', '2025-04-20', 2016, 22000, 160, 6, 20000, 60, 16.8661, 96.1951, 'active', NOW()),
(@company_id, 'Addis Garment PLC', 'SUP-034', 'Addis Factory Zone', 'Ethiopia', 'Addis Ababa', 'full_package', 'Tadesse Bekele', 'tadesse@addisgarment.et', '+251-91-234-5678', 'pending_qualification', 0, 'medium', NULL, 2019, 28000, 200, 8, 30000, 55, 9.0250, 38.7469, 'active', NOW()),
(@company_id, 'National Threads', 'SUP-035', 'NT Dyeing Unit', 'Bangladesh', 'Narayanganj', 'chemical', 'Habib Rahman', 'habib@nationalethreads.com', '+880-171-555-0808', 'conditional', 72.80, 'medium', '2025-10-15', 2004, 25000, 150, 0, 0, 40, 23.6234, 90.5000, 'active', NOW());


-- ============================================================
-- 2. SUPPLIER CERTIFICATIONS
-- ============================================================
INSERT INTO supplier_certifications (supplier_id, certification_type, certification_name, issuing_body, certificate_number, issue_date, expiry_date, status, created_at)
SELECT sp.id, cert.cert_type, cert.cert_name, cert.issuing_body, cert.cert_number, cert.issued_date, cert.expiry_date, 'valid', NOW()
FROM supplier_profiles sp
CROSS JOIN (
    SELECT 'iso_9001' as cert_type, 'ISO 9001:2015' as cert_name, 'Bureau Veritas' as issuing_body, 'ISO-9001-2024-001' as cert_number, '2024-01-15' as issued_date, '2027-01-14' as expiry_date
    UNION ALL SELECT 'iso_14001', 'ISO 14001:2015', 'SGS', 'ISO-14001-2024-002', '2024-03-20', '2027-03-19'
    UNION ALL SELECT 'oeko_tex', 'OEKO-TEX Standard 100', 'OEKO-TEX Association', 'OEKO-TEX-100-2024', '2024-06-01', '2025-05-31'
) cert
WHERE sp.supplier_code IN ('SUP-017','SUP-018','SUP-020','SUP-021','SUP-023','SUP-025','SUP-027','SUP-029','SUP-031','SUP-032')
AND NOT EXISTS (SELECT 1 FROM supplier_certifications sc WHERE sc.supplier_id = sp.id AND sc.certification_type = cert.cert_type)
LIMIT 30;


-- ============================================================
-- 3. PORTAL INVITES (for several suppliers)
-- ============================================================
INSERT INTO supplier_portal_invites (supplier_id, company_id, invited_by, token, status, expires_at, created_at)
SELECT sp.id, @company_id, 1,
    CONCAT('test_inv_', LOWER(REPLACE(sp.supplier_code, '-', '_')), '_', UNIX_TIMESTAMP()),
    CASE
        WHEN sp.supplier_code IN ('SUP-017','SUP-020','SUP-023') THEN 'activated'
        WHEN sp.supplier_code = 'SUP-025' THEN 'submitted'
        ELSE 'pending'
    END,
    DATE_ADD(NOW(), INTERVAL 30 DAY),
    DATE_SUB(NOW(), INTERVAL FLOOR(RAND() * 30) DAY)
FROM supplier_profiles sp
WHERE sp.supplier_code IN ('SUP-017','SUP-018','SUP-020','SUP-023','SUP-025','SUP-027','SUP-029')
AND NOT EXISTS (SELECT 1 FROM supplier_portal_invites pi WHERE pi.supplier_id = sp.id);


-- ============================================================
-- 4. PORTAL USER ACCOUNTS (for activated invites)
-- ============================================================
INSERT INTO supplier_portal_users (supplier_id, name, email, password_hash, phone, role, status, created_at)
SELECT pi.supplier_id, sp.contact_person, sp.contact_email,
    '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',  -- password: "password"
    sp.contact_phone, 'admin', 'active', NOW()
FROM supplier_portal_invites pi
JOIN supplier_profiles sp ON pi.supplier_id = sp.id
WHERE pi.status IN ('activated', 'submitted')
AND NOT EXISTS (SELECT 1 FROM supplier_portal_users pu WHERE pu.supplier_id = pi.supplier_id);


-- ============================================================
-- 5. PORTAL SUBMISSIONS (for activated invites)
-- ============================================================
INSERT INTO supplier_portal_submissions (
    invite_id, supplier_id, company_name, factory_name, factory_address, city, state, country,
    contact_person, contact_email, contact_phone, year_established, facility_size_sqft,
    total_employees, num_sewing_lines, monthly_capacity, lead_time_days,
    supplier_type, progress_pct, current_step, status, created_at
)
SELECT pi.id, pi.supplier_id, sp.supplier_name, sp.factory_name,
    CONCAT(sp.factory_name, ', Industrial Area, ', sp.city), sp.city, '', sp.country,
    sp.contact_person, sp.contact_email, sp.contact_phone,
    sp.year_established, sp.facility_size_sqft, sp.total_employees,
    sp.num_sewing_lines, sp.monthly_capacity, sp.lead_time_days,
    sp.supplier_type,
    CASE pi.status WHEN 'submitted' THEN 100 WHEN 'activated' THEN 60 ELSE 20 END,
    CASE pi.status WHEN 'submitted' THEN 5 WHEN 'activated' THEN 3 ELSE 1 END,
    CASE pi.status WHEN 'submitted' THEN 'submitted' WHEN 'activated' THEN 'draft' ELSE 'draft' END,
    NOW()
FROM supplier_portal_invites pi
JOIN supplier_profiles sp ON pi.supplier_id = sp.id
WHERE NOT EXISTS (SELECT 1 FROM supplier_portal_submissions ps WHERE ps.supplier_id = pi.supplier_id);


-- ============================================================
-- 6. AUDITS (mix of statuses across suppliers)
-- ============================================================

-- Planned audits (upcoming)
INSERT IGNORE INTO supplier_audits (
    company_id, supplier_id, audit_code, audit_type, audit_status, audit_date,
    auditor_name, audit_scope, overall_score, audit_decision, created_at
) VALUES
(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-018'), 'AUD-2026-017', 'routine', 'planned', DATE_ADD(CURDATE(), INTERVAL 5 DAY),
 'John Smith', 'Full factory audit covering quality, compliance, and production processes', 0, 'pending', NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-022'), 'AUD-2026-018', 'follow_up', 'planned', DATE_ADD(CURDATE(), INTERVAL 10 DAY),
 'John Smith', 'Follow-up audit for previously identified non-conformances', 0, 'pending', NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-030'), 'AUD-2026-019', 'initial_qualification', 'planned', DATE_ADD(CURDATE(), INTERVAL 15 DAY),
 'Sarah Johnson', 'Initial qualification audit for new supplier onboarding', 0, 'pending', NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-034'), 'AUD-2026-020', 'initial_qualification', 'planned', DATE_ADD(CURDATE(), INTERVAL 20 DAY),
 'Sarah Johnson', 'Initial qualification audit — Ethiopia facility', 0, 'pending', NOW());

-- In-progress audit (today)
INSERT IGNORE INTO supplier_audits (
    company_id, supplier_id, audit_code, audit_type, audit_status, audit_date,
    auditor_name, audit_scope, overall_score, audit_decision, created_at
) VALUES
(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-019'), 'AUD-2026-021', 'surveillance', 'in_progress', CURDATE(),
 'John Smith', 'Surveillance audit — production quality and compliance', 0, 'pending', NOW());

-- Completed audits (recent past)
INSERT IGNORE INTO supplier_audits (
    company_id, supplier_id, audit_code, audit_type, audit_status, audit_date,
    auditor_name, audit_scope, overall_score, quality_score, compliance_score, production_score,
    total_checklist_items, passed_items, failed_items, na_items,
    major_ncr_count, minor_ncr_count, observation_count,
    audit_decision, decision_notes, executive_summary, strengths, weaknesses, created_at
) VALUES
(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-017'), 'AUD-2026-010', 'routine', 'completed', DATE_SUB(CURDATE(), INTERVAL 30 DAY),
 'John Smith', 'Routine annual audit', 87.50, 90.00, 85.00, 88.00,
 85, 74, 8, 3, 2, 4, 2,
 'approved', 'Supplier meets all quality standards. Minor improvements recommended.',
 'Comprehensive audit covering all production areas. Strong quality management system in place.',
 'Excellent documentation, well-trained workforce, modern equipment', 'Some housekeeping issues in warehouse area, minor calibration gaps',
 NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-020'), 'AUD-2026-011', 'routine', 'completed', DATE_SUB(CURDATE(), INTERVAL 25 DAY),
 'Sarah Johnson', 'Annual quality system audit', 91.30, 93.00, 90.00, 92.00,
 90, 83, 5, 2, 1, 3, 1,
 'approved', 'Outstanding performance. Supplier exceeds expectations.',
 'Top-tier supplier with excellent quality management and compliance culture.',
 'ISO-certified processes, proactive quality team, zero major NCRs in last 3 audits', 'Minor documentation gaps in chemical management section',
 NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-019'), 'AUD-2026-012', 'follow_up', 'completed', DATE_SUB(CURDATE(), INTERVAL 20 DAY),
 'John Smith', 'Follow-up on previous NCRs', 68.20, 65.00, 70.00, 68.00,
 75, 51, 18, 6, 5, 8, 5,
 'conditional_approval', 'Significant improvement needed in production processes. 30-day corrective action plan required.',
 'Follow-up audit revealed persistent issues in cutting and finishing departments.',
 'Good management commitment, responsive to feedback', 'Persistent quality issues in finishing, inadequate training records, poor housekeeping',
 NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-023'), 'AUD-2026-013', 'initial_qualification', 'completed', DATE_SUB(CURDATE(), INTERVAL 15 DAY),
 'Sarah Johnson', 'Initial qualification audit', 89.70, 91.00, 88.00, 90.00,
 88, 80, 6, 2, 1, 4, 1,
 'approved', 'New supplier meets all qualification criteria. Recommended for approved status.',
 'Well-equipped facility with strong production capabilities. Good compliance framework.',
 'Modern machinery, skilled workforce, strong safety culture', 'Minor gaps in environmental management documentation',
 NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-025'), 'AUD-2026-014', 'routine', 'completed', DATE_SUB(CURDATE(), INTERVAL 10 DAY),
 'John Smith', 'Annual audit — fabric supplier', 93.40, 95.00, 92.00, 94.00,
 92, 87, 3, 2, 0, 2, 1,
 'approved', 'Exceptional supplier. Best-in-class quality management.',
 'Highest-scoring supplier in current audit cycle. Exceeds all quality benchmarks.',
 'Zero major NCRs, excellent calibration program, strong continuous improvement culture', 'Minor cosmetic issues in raw material storage area',
 NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-027'), 'AUD-2026-015', 'technical', 'completed', DATE_SUB(CURDATE(), INTERVAL 8 DAY),
 'Sarah Johnson', 'Technical capability assessment', 95.20, 97.00, 94.00, 96.00,
 95, 91, 3, 1, 0, 2, 1,
 'approved', 'World-class technical capabilities. Exceeds industry standards.',
 'Exceptional technical infrastructure and process control. Reference facility.',
 'State-of-the-art equipment, advanced quality labs, Industry 4.0 implementation', 'Minor improvement opportunities in documentation digitalization',
 NOW()),

(@company_id, (SELECT id FROM supplier_profiles WHERE supplier_code='SUP-028'), 'AUD-2026-016', 'social_compliance', 'completed', DATE_SUB(CURDATE(), INTERVAL 5 DAY),
 'John Smith', 'Social compliance and labor audit', 65.30, 60.00, 70.00, 66.00,
 80, 52, 22, 6, 6, 10, 6,
 'rejected', 'Critical non-conformances found. Immediate corrective action required before re-audit.',
 'Multiple critical findings related to working hours, overtime records, and safety equipment.',
 'Cooperative management, basic safety equipment in place', 'Excessive overtime, missing overtime records, inadequate fire safety training, blocked emergency exits',
 NOW());


-- ============================================================
-- 7. AUDIT SECTIONS (for completed audits)
-- ============================================================
INSERT INTO supplier_audit_sections (
    audit_id, section_key, section_name, section_order, max_score, score, weighted_score,
    total_items, passed_items, failed_items, na_items, status, notes
)
SELECT sa.id, LOWER(REPLACE(REPLACE(sec.section_name, ' ', '_'), '&', 'and')), sec.section_name, sec.section_order, sec.max_score,
    ROUND(sec.max_score * (0.6 + RAND() * 0.4)),  -- Random score between 60-100% of max
    sec.max_score,
    sec.total_items,
    GREATEST(0, sec.total_items - FLOOR(RAND() * 4)),
    FLOOR(RAND() * 3),
    FLOOR(RAND() * 2),
    CASE WHEN RAND() > 0.3 THEN 'completed' ELSE 'in_progress' END,
    NULL
FROM supplier_audits sa
CROSS JOIN (
    SELECT 'Quality Management System' as section_name, 1 as section_order, 100 as max_score, 12 as total_items
    UNION ALL SELECT 'Production Process', 2, 100, 15
    UNION ALL SELECT 'Raw Material Management', 3, 100, 10
    UNION ALL SELECT 'In-Process Quality Control', 4, 100, 14
    UNION ALL SELECT 'Final Inspection & Testing', 5, 100, 12
    UNION ALL SELECT 'Facility & Equipment', 6, 100, 10
    UNION ALL SELECT 'Health & Safety', 7, 100, 11
    UNION ALL SELECT 'Environmental Management', 8, 100, 8
    UNION ALL SELECT 'Documentation & Records', 9, 100, 8
) sec
WHERE sa.audit_status = 'completed'
AND sa.audit_code LIKE 'AUD-2026-%'
AND NOT EXISTS (SELECT 1 FROM supplier_audit_sections sas WHERE sas.audit_id = sa.id);


-- ============================================================
-- 8. CHECKLIST ITEMS (for each section)
-- ============================================================
INSERT INTO supplier_audit_checklists (
    audit_id, section_id, question, item_order, status, answer_score, max_score, finding
)
SELECT sas.audit_id, sas.id, cli.item_name, cli.item_order,
    CASE
        WHEN RAND() > 0.15 THEN 'pass'
        WHEN RAND() > 0.5 THEN 'fail'
        ELSE 'na'
    END,
    CASE
        WHEN RAND() > 0.15 THEN sas.max_score / sas.total_items
        WHEN RAND() > 0.5 THEN 0
        ELSE NULL
    END,
    sas.max_score / sas.total_items,
    NULL
FROM supplier_audit_sections sas
CROSS JOIN (
    SELECT 'QMS-01: Quality policy documented' as item_name, 1 as item_order
    UNION ALL SELECT 'QMS-02: Management review records', 2
    UNION ALL SELECT 'QMS-03: Internal audit program', 3
    UNION ALL SELECT 'QMS-04: Corrective action process', 4
    UNION ALL SELECT 'QMS-05: Document control system', 5
    UNION ALL SELECT 'PRD-01: Production planning process', 1
    UNION ALL SELECT 'PRD-02: Work instructions available', 2
    UNION ALL SELECT 'PRD-03: Line balancing adequate', 3
    UNION ALL SELECT 'PRD-04: Sample approval process', 4
    UNION ALL SELECT 'PRD-05: Production tracking system', 5
    UNION ALL SELECT 'PRD-06: Change management process', 6
    UNION ALL SELECT 'RML-01: Incoming material inspection', 1
    UNION ALL SELECT 'RML-02: Supplier evaluation process', 2
    UNION ALL SELECT 'RML-03: Material storage conditions', 3
    UNION ALL SELECT 'RML-04: FIFO system implemented', 4
    UNION ALL SELECT 'IPC-01: In-line inspection coverage', 1
    UNION ALL SELECT 'IPC-02: Defect tracking system', 2
    UNION ALL SELECT 'IPC-03: Measurement tools calibrated', 3
    UNION ALL SELECT 'IPC-04: AQL standards followed', 4
    UNION ALL SELECT 'FIN-01: Final inspection procedure', 1
    UNION ALL SELECT 'FIN-02: Packaging standards met', 2
    UNION ALL SELECT 'FIN-03: Labeling accuracy', 3
    UNION ALL SELECT 'FAC-01: Equipment maintenance schedule', 1
    UNION ALL SELECT 'FAC-02: Machinery in good condition', 2
    UNION ALL SELECT 'FAC-03: Backup power available', 3
    UNION ALL SELECT 'HSE-01: Fire extinguishers accessible', 1
    UNION ALL SELECT 'HSE-02: Emergency exits clear', 2
    UNION ALL SELECT 'HSE-03: PPE provided and used', 3
    UNION ALL SELECT 'HSE-04: First aid kits stocked', 4
    UNION ALL SELECT 'ENV-01: Waste management system', 1
    UNION ALL SELECT 'ENV-02: Water treatment (if applicable)', 2
    UNION ALL SELECT 'ENV-03: Chemical storage compliant', 3
    UNION ALL SELECT 'DOC-01: Records maintained per retention policy', 1
    UNION ALL SELECT 'DOC-02: Training records current', 2
    UNION ALL SELECT 'DOC-03: Calibration certificates available', 3
) cli
JOIN supplier_audits sa ON sa.id = sas.audit_id
WHERE sa.audit_code LIKE 'AUD-2026-%'
AND NOT EXISTS (SELECT 1 FROM supplier_audit_checklists sac WHERE sac.audit_id = sas.audit_id AND sac.section_id = sas.id)
LIMIT 500;


-- ============================================================
-- 9. NCRs (Non-Conformance Reports)
-- ============================================================
INSERT INTO supplier_audit_ncr (
    audit_id, ncr_code, title, description, severity, status, category,
    root_cause, corrective_action, target_date, created_at
)
SELECT sa.id,
    CONCAT('NCR-2026-', LPAD(@rownum := @rownum + 1, 3, '0')),
    ncr.title, ncr.description, ncr.severity, ncr.status, 'quality',
    ncr.root_cause, ncr.corrective_action,
    DATE_ADD(sa.audit_date, INTERVAL ncr.days_to_target DAY),
    sa.created_at
FROM supplier_audits sa
CROSS JOIN (SELECT @rownum := 44) r
CROSS JOIN (
    SELECT 'Cutting defects exceeding AQL' as title, 'Multiple cutting defects found during final inspection. Defect rate 3.2% vs 2.5% AQL.' as description, 'major' as severity, 'corrective_action' as status, 'Inadequate cutting blade maintenance and operator training' as root_cause, 'Increased inspection frequency on cutting section' as containment_action, 'Implement weekly blade replacement schedule and operator retraining' as corrective_action, 30 as days_to_target
    UNION ALL SELECT 'Missing calibration certificates', '3 measuring instruments found without valid calibration certificates.', 'major', 'root_cause', 'Calibration tracking system not maintained', 'Instruments quarantined pending calibration', 'Implement digital calibration tracking system', 14
    UNION ALL SELECT 'Blocked emergency exit', 'Emergency exit in production floor blocked by stored materials.', 'critical', 'open', 'Insufficient storage space and poor housekeeping', 'Exit cleared immediately', 'Reorganize storage area, install signage, conduct housekeeping training', 7
    UNION ALL SELECT 'Excessive overtime records', 'Workers recorded 72+ hour weeks for 3 consecutive weeks.', 'critical', 'containment', 'Production planning deficiencies', 'Temporarily reduced order intake', 'Hire additional staff, improve production planning, implement overtime approval process', 21
    UNION ALL SELECT 'PPE not worn by operators', 'Multiple operators observed without safety goggles in cutting section.', 'major', 'corrective_action', 'Lack of enforcement and training', 'Verbal warning issued to supervisors', 'Install PPE compliance monitoring, mandatory safety training', 14
    UNION ALL SELECT 'Chemical labeling incomplete', '3 chemical containers in dyeing section missing proper hazard labels.', 'major', 'closed', 'Labeling supplies ran out', 'Labels replaced immediately', 'Implement chemical inventory management with automatic label reorder', 21
    UNION ALL SELECT 'Raw material storage temperature', 'Fabric storage area temperature exceeded recommended range.', 'minor', 'closed', 'HVAC system undersized for area', 'Portable cooling units deployed', 'Upgrade HVAC system for storage area', 30
    UNION ALL SELECT 'Document version control', 'Old revision work instructions found at 2 workstation stations.', 'minor', 'corrective_action', 'Document distribution process gaps', 'Old documents collected and destroyed', 'Implement digital document management system', 45
) ncr
WHERE sa.audit_code LIKE 'AUD-2026-%'
AND sa.audit_status = 'completed'
AND NOT EXISTS (SELECT 1 FROM supplier_audit_ncr n WHERE n.audit_id = sa.id);


-- ============================================================
-- 10. CAPAs (Corrective/Preventive Actions)
-- ============================================================
INSERT INTO supplier_audit_capa (
    audit_id, ncr_id, capa_code, capa_type, title, description,
    responsible_person, target_date, status, root_cause,
    action_plan, created_at
)
SELECT ncr.audit_id, ncr.id,
    CONCAT('CAPA-2026-', LPAD(@rownum2 := @rownum2 + 1, 3, '0')),
    CASE WHEN ncr.severity IN ('critical', 'major') THEN 'corrective' ELSE 'preventive' END,
    CONCAT('Action for: ', ncr.title),
    CONCAT('Addressing NCR: ', ncr.description),
    CASE WHEN RAND() > 0.5 THEN 'John Smith' ELSE 'Sarah Johnson' END,
    DATE_ADD(CURDATE(), INTERVAL FLOOR(10 + RAND() * 50) DAY),
    CASE
        WHEN ncr.status = 'closed' THEN 'completed'
        WHEN RAND() > 0.7 THEN 'in_progress'
        WHEN RAND() > 0.4 THEN 'pending_verification'
        ELSE 'open'
    END,
    ncr.root_cause,
    ncr.corrective_action,
    ncr.created_at
FROM supplier_audit_ncr ncr
CROSS JOIN (SELECT @rownum2 := 34) r
WHERE ncr.audit_id IN (SELECT id FROM supplier_audits WHERE audit_code LIKE 'AUD-2026-%' AND audit_status = 'completed')
AND NOT EXISTS (SELECT 1 FROM supplier_audit_capa c WHERE c.ncr_id = ncr.id);


-- ============================================================
-- 11. AUDIT IMAGES
-- ============================================================
INSERT INTO supplier_audit_images (
    audit_id, file_name, file_path, image_type, caption, created_at
)
SELECT sa.id,
    CONCAT('audit_', sa.id, '_', FLOOR(RAND() * 1000), '.jpg'),
    CONCAT('/uploads/supplier-audit-images/audit_', sa.id, '.jpg'),
    ELT(FLOOR(1 + RAND() * 5), 'factory_entrance', 'production_floor', 'warehouse', 'laboratory', 'office'),
    ELT(FLOOR(1 + RAND() * 5), 'Factory entrance view', 'Production floor overview', 'Raw material warehouse', 'Quality testing lab', 'Office area'),
    sa.created_at
FROM supplier_audits sa
CROSS JOIN (SELECT 1 UNION SELECT 2 UNION SELECT 3) t
WHERE sa.audit_code LIKE 'AUD-2026-%'
AND sa.audit_status = 'completed'
AND NOT EXISTS (SELECT 1 FROM supplier_audit_images sai WHERE sai.audit_id = sa.id);


-- ============================================================
-- 12. AUDIT APPROVALS
-- ============================================================
INSERT INTO supplier_audit_approvals (
    audit_id, approver_name, approver_role, status, comments, approved_at, created_at
)
SELECT sa.id,
    CASE
        WHEN seq.level = 1 THEN 'Quality Manager'
        WHEN seq.level = 2 THEN 'Director'
        ELSE 'Final Reviewer'
    END,
    CASE
        WHEN seq.level = 1 THEN 'quality_manager'
        WHEN seq.level = 2 THEN 'director'
        ELSE 'reviewer'
    END,
    CASE
        WHEN sa.audit_decision = 'approved' THEN 'approved'
        WHEN sa.audit_decision = 'rejected' THEN 'rejected'
        WHEN seq.level <= 2 THEN 'approved'
        ELSE 'pending'
    END,
    CASE
        WHEN sa.audit_decision = 'approved' THEN 'Reviewed and approved'
        WHEN sa.audit_decision = 'rejected' THEN 'Does not meet requirements'
        ELSE NULL
    END,
    CASE WHEN seq.level <= 2 OR sa.audit_decision IN ('approved','rejected') THEN sa.updated_at ELSE NULL END,
    sa.created_at
FROM supplier_audits sa
CROSS JOIN (SELECT 1 as level UNION SELECT 2 UNION SELECT 3) seq
WHERE sa.audit_code LIKE 'AUD-2026-%'
AND sa.audit_status = 'completed'
AND NOT EXISTS (SELECT 1 FROM supplier_audit_approvals saa WHERE saa.audit_id = sa.id);


-- ============================================================
-- 13. RISK PROFILES
-- ============================================================
INSERT INTO supplier_risk_profiles (
    supplier_id, assessment_date, overall_risk, quality_risk, delivery_risk,
    compliance_risk, financial_risk, assessed_by, created_at
)
SELECT sp.id,
    COALESCE(sp.last_audit_date, CURDATE()),
    CASE
        WHEN sp.overall_score >= 90 THEN 'low'
        WHEN sp.overall_score >= 75 THEN 'medium'
        WHEN sp.overall_score >= 50 THEN 'high'
        WHEN sp.overall_score > 0 THEN 'critical'
        ELSE 'medium'
    END,
    CASE WHEN RAND() > 0.5 THEN 'low' ELSE 'medium' END,
    CASE WHEN RAND() > 0.5 THEN 'low' ELSE 'medium' END,
    CASE WHEN RAND() > 0.5 THEN 'low' ELSE 'medium' END,
    CASE WHEN RAND() > 0.5 THEN 'low' ELSE 'medium' END,
    'System',
    NOW()
FROM supplier_profiles sp
WHERE NOT EXISTS (SELECT 1 FROM supplier_risk_profiles srp WHERE srp.supplier_id = sp.id);


-- ============================================================
-- 14. PERFORMANCE HISTORY
-- ============================================================
INSERT INTO supplier_performance_history (
    supplier_id, period_start, period_end, quality_pass_rate, overall_score, rating, notes, created_at
)
SELECT sa.supplier_id, sa.audit_date, sa.audit_date,
    CASE WHEN sa.passed_items > 0 THEN ROUND(sa.passed_items * 100.0 / GREATEST(sa.total_checklist_items, 1), 2) ELSE 0 END,
    sa.overall_score,
    CASE WHEN sa.overall_score >= 90 THEN 'A' WHEN sa.overall_score >= 75 THEN 'B' WHEN sa.overall_score >= 60 THEN 'C' ELSE 'D' END,
    CONCAT('Audit ', sa.audit_code, ' — ', sa.audit_decision),
    NOW()
FROM supplier_audits sa
WHERE sa.audit_status = 'completed'
AND sa.audit_code LIKE 'AUD-2026-%'
AND NOT EXISTS (
    SELECT 1 FROM supplier_performance_history sph
    WHERE sph.supplier_id = sa.supplier_id AND sph.period_start = sa.audit_date
);


-- ============================================================
-- 15. CAPA TIMELINE (for some CAPAs)
-- ============================================================
INSERT INTO supplier_capa_timeline (capa_id, action_type, action_by, action_notes, new_status, created_at)
SELECT c.id, 'viewed', 'System', 'CAPA viewed by supplier portal', c.status, c.created_at
FROM supplier_audit_capa c
WHERE c.capa_code LIKE 'CAPA-2026-%'
AND RAND() > 0.5
AND NOT EXISTS (SELECT 1 FROM supplier_capa_timeline ct WHERE ct.capa_id = c.id);


-- ============================================================
-- DONE
-- ============================================================
SELECT 'Seed complete!' as status,
    (SELECT COUNT(*) FROM supplier_profiles) as total_suppliers,
    (SELECT COUNT(*) FROM supplier_audits) as total_audits,
    (SELECT COUNT(*) FROM supplier_audit_ncr) as total_ncrs,
    (SELECT COUNT(*) FROM supplier_audit_capa) as total_capas,
    (SELECT COUNT(*) FROM supplier_portal_users) as portal_users,
    (SELECT COUNT(*) FROM supplier_portal_invites) as portal_invites;


-- ============================================================
-- FILE: migration_seasons.sql
-- ============================================================

CREATE TABLE IF NOT EXISTS `master_seasons` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_name` varchar(100) NOT NULL,
  `season_type` varchar(50) DEFAULT NULL,
  `season_code` varchar(20) NOT NULL DEFAULT '',
  `department` varchar(100) DEFAULT NULL,
  `description` text,
  `default_currency` varchar(3) DEFAULT NULL,
  `year` smallint DEFAULT NULL,
  `start_date` date DEFAULT NULL,
  `end_date` date DEFAULT NULL,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `approval_status` enum('draft','submitted','approved','rejected') NOT NULL DEFAULT 'draft',
  `approval_note` varchar(255) DEFAULT NULL,
  `share_token` varchar(64) DEFAULT NULL,
  `version_label` varchar(20) 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`),
  KEY `company_id` (`company_id`),
  KEY `season_type` (`season_type`),
  KEY `share_token` (`share_token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT IGNORE INTO `master_seasons` (`id`, `company_id`, `season_name`, `season_type`, `season_code`, `year`, `start_date`, `end_date`, `status`) VALUES
(1, 1, 'Spring/Summer 2025', 'Spring Summer', 'SS25', 2025, '2025-01-01', '2025-06-30', 'active'),
(2, 1, 'Fall/Winter 2025', 'Autumn Winter', 'FW25', 2025, '2025-07-01', '2025-12-31', 'active'),
(3, 1, 'Spring/Summer 2026', 'Spring Summer', 'SS26', 2026, '2026-01-01', '2026-06-30', 'active'),
(4, 1, 'Fall/Winter 2026', 'Autumn Winter', 'FW26', 2026, '2026-07-01', '2026-12-31', 'active'),
(5, 1, 'Resort 2025', 'Resort', 'RS25', 2025, '2025-11-01', '2026-03-31', 'active'),
(6, 1, 'Pre-Fall 2025', 'Custom', 'PF25', 2025, '2025-04-01', '2025-08-31', 'active'),
(7, 1, 'Capsule Collection', 'Capsule Collection', 'CC', NULL, NULL, NULL, 'active'),
(8, 1, 'Core/Basic', 'Core', 'CB', NULL, NULL, NULL, 'active'),
(9, 1, 'Autumn/Winter 2026', 'Autumn Winter', 'AW26', 2026, '2026-07-01', '2026-12-31', 'active'),
(10, 1, 'Spring/Summer 2027', 'Spring Summer', 'SS27', 2027, '2027-01-01', '2027-06-30', 'active'),
(11, 1, 'Autumn/Winter 2027', 'Autumn Winter', 'AW27', 2027, '2027-07-01', '2027-12-31', 'active'),
(12, 1, 'Holiday 2026', 'Holiday', 'HOL26', 2026, '2026-11-01', '2026-12-31', 'active'),
(13, 1, 'Resort 2027', 'Resort', 'RES27', 2027, '2026-11-01', '2027-03-31', 'active'),
(14, 1, 'Core Collection', 'Core', 'CORE', NULL, NULL, NULL, 'active'),
(15, 1, 'Never Out of Stock', 'Never Out of Stock', 'NOS', NULL, NULL, NULL, 'active'),
(16, 1, 'Capsule Collection 2026', 'Capsule Collection', 'CAPS26', 2026, '2026-09-01', '2026-10-31', 'active'),
(17, 1, 'Back to School 2026', 'Back To School', 'BTS26', 2026, '2026-07-01', '2026-08-31', 'active');

-- ============================================================
-- Phase 1: Digital Season Workspace tables
-- ============================================================
CREATE TABLE IF NOT EXISTS `season_calendars` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `milestone` varchar(100) NOT NULL,
  `sort_order` int NOT NULL DEFAULT 0,
  `planned_date` date DEFAULT NULL,
  `actual_date` date DEFAULT NULL,
  `status` enum('pending','completed','overdue','skipped') NOT NULL DEFAULT 'pending',
  `notes` varchar(255) 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`),
  KEY `company_id` (`company_id`),
  KEY `season_id` (`season_id`),
  KEY `season_milestone` (`season_id`, `milestone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_collections` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `collection_name` varchar(150) NOT NULL,
  `brand_id` int unsigned DEFAULT NULL,
  `brand_name` varchar(255) DEFAULT NULL,
  `description` text,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `season_id` (`season_id`),
  KEY `brand_id` (`brand_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_delivery_windows` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `drop_no` int DEFAULT NULL,
  `window_name` varchar(100) DEFAULT NULL,
  `start_date` date DEFAULT NULL,
  `end_date` date DEFAULT NULL,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `season_id` (`season_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_buyer_mapping` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `buyer_id` int unsigned NOT NULL,
  `buyer_season_code` varchar(50) DEFAULT NULL,
  `notes` varchar(255) 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 `uq_season_buyer` (`season_id`, `buyer_id`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_brand_mapping` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `brand_name` varchar(255) NOT NULL,
  `collection_id` int unsigned DEFAULT NULL,
  `notes` varchar(255) 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 `uq_season_brand` (`season_id`, `brand_name`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Add season_id foreign key to master_styles
ALTER TABLE `master_styles` ADD COLUMN `season_id` int unsigned DEFAULT NULL AFTER `season`;
ALTER TABLE `master_styles` ADD KEY `season_id` (`season_id`);

-- ============================================================
-- Phase 2: AI Planning Engine tables
-- ============================================================
CREATE TABLE IF NOT EXISTS `season_ai` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `analysis_type` enum('forecast','colors','fabrics','delivery','risk') NOT NULL,
  `payload` json DEFAULT NULL,
  `method` varchar(100) DEFAULT 'heuristic',
  `run_count` int NOT NULL DEFAULT 1,
  `created_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 `uq_season_type` (`season_id`, `analysis_type`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_color_themes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `color_name` varchar(100) NOT NULL,
  `hex_code` varchar(9) DEFAULT NULL,
  `sort_order` int NOT NULL DEFAULT 0,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `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 `uq_season_color` (`season_id`, `color_name`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_fabric_themes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `fabric_name` varchar(150) NOT NULL,
  `sort_order` int NOT NULL DEFAULT 0,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `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 `uq_season_fabric` (`season_id`, `fabric_name`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- Phase 3: Documents, QR, Print, Approvals & Version History
-- ============================================================
CREATE TABLE IF NOT EXISTS `season_documents` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `category` varchar(100) DEFAULT 'other',
  `file_path` varchar(500) NOT NULL,
  `notes` varchar(255) DEFAULT NULL,
  `created_by` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `season_id` (`season_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_history` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `action` varchar(100) NOT NULL,
  `field` varchar(100) DEFAULT NULL,
  `old_value` text,
  `new_value` text,
  `user_id` int unsigned DEFAULT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `note` text,
  `version_label` varchar(20) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `season_id` (`season_id`),
  KEY `created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `season_approvals` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `season_id` int unsigned NOT NULL,
  `status` enum('submitted','approved','rejected') NOT NULL,
  `acted_by` int unsigned DEFAULT NULL,
  `acted_by_name` varchar(255) DEFAULT NULL,
  `note` varchar(500) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `season_id` (`season_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ============================================================
-- FILE: migration_incoterms.sql
-- ============================================================

CREATE TABLE IF NOT EXISTS `master_incoterms` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `incoterm_code` varchar(10) NOT NULL,
  `incoterm_name` varchar(255) NOT NULL,
  `description` text,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `master_incoterms` (`company_id`, `incoterm_code`, `incoterm_name`, `description`, `status`) VALUES
(1, 'EXW', 'Ex Works', 'Seller makes goods available at their premises. Buyer bears all costs and risks from that point.', 'active'),
(1, 'FCA', 'Free Carrier', 'Seller delivers goods to the carrier nominated by the buyer at the named place.', 'active'),
(1, 'FAS', 'Free Alongside Ship', 'Seller delivers goods alongside the vessel at the named port of shipment.', 'active'),
(1, 'FOB', 'Free On Board', 'Seller delivers goods on board the vessel at the named port of shipment. Risk transfers when goods are on board.', 'active'),
(1, 'CFR', 'Cost and Freight', 'Seller delivers goods on board the vessel and pays freight to the named port of destination. Risk transfers on board.', 'active'),
(1, 'CIF', 'Cost, Insurance & Freight', 'Seller delivers goods on board the vessel, pays freight and procures marine insurance to the named port of destination.', 'active'),
(1, 'CPT', 'Carriage Paid To', 'Seller pays freight to the named destination. Risk transfers when goods are delivered to the carrier.', 'active'),
(1, 'CIP', 'Carriage & Insurance Paid To', 'Seller pays freight and insurance to the named destination. Risk transfers when goods are delivered to the carrier.', 'active'),
(1, 'DAP', 'Delivered at Place', 'Seller delivers goods ready for unloading at the named destination. Seller bears all risks.', 'active'),
(1, 'DPU', 'Delivered at Place Unloaded', 'Seller delivers goods unloaded at the named destination. Seller bears all risks and unloading costs.', 'active'),
(1, 'DDP', 'Delivered Duty Paid', 'Seller delivers goods cleared for import at the named destination. Seller bears all risks and costs including duties and taxes.', 'active');


-- ============================================================
-- FILE: migration_pantone_code.sql
-- ============================================================

ALTER TABLE `master_colors`
  ADD COLUMN `pantone_code` varchar(20) NOT NULL DEFAULT '' AFTER `hex_code`;

UPDATE `master_colors` SET `pantone_code` = '19-4052 TCX' WHERE `color_name` = 'Navy';
UPDATE `master_colors` SET `pantone_code` = '11-0602 TCX' WHERE `color_name` = 'White';
UPDATE `master_colors` SET `pantone_code` = '19-0303 TCX' WHERE `color_name` = 'Black';
UPDATE `master_colors` SET `pantone_code` = '18-1763 TCX' WHERE `color_name` = 'Red';
UPDATE `master_colors` SET `pantone_code` = '18-3943 TCX' WHERE `color_name` = 'Royal Blue';
UPDATE `master_colors` SET `pantone_code` = '14-4318 TCX' WHERE `color_name` = 'Sky Blue';
UPDATE `master_colors` SET `pantone_code` = '13-2010 TCX' WHERE `color_name` = 'Light Pink';
UPDATE `master_colors` SET `pantone_code` = '17-2034 TCX' WHERE `color_name` = 'Hot Pink';
UPDATE `master_colors` SET `pantone_code` = '19-1535 TCX' WHERE `color_name` = 'Maroon';
UPDATE `master_colors` SET `pantone_code` = '19-1536 TCX' WHERE `color_name` = 'Burgundy';
UPDATE `master_colors` SET `pantone_code` = '18-6024 TCX' WHERE `color_name` = 'Forest Green';
UPDATE `master_colors` SET `pantone_code` = '17-0530 TCX' WHERE `color_name` = 'Olive';
UPDATE `master_colors` SET `pantone_code` = '15-1132 TCX' WHERE `color_name` = 'Khaki';
UPDATE `master_colors` SET `pantone_code` = '12-0605 TCX' WHERE `color_name` = 'Beige';
UPDATE `master_colors` SET `pantone_code` = '17-4402 TCX' WHERE `color_name` = 'Grey';
UPDATE `master_colors` SET `pantone_code` = '18-0615 TCX' WHERE `color_name` = 'Charcoal';
UPDATE `master_colors` SET `pantone_code` = '14-0848 TCX' WHERE `color_name` = 'Yellow';
UPDATE `master_colors` SET `pantone_code` = '15-1150 TCX' WHERE `color_name` = 'Orange';
UPDATE `master_colors` SET `pantone_code` = '16-1546 TCX' WHERE `color_name` = 'Coral';
UPDATE `master_colors` SET `pantone_code` = '18-3027 TCX' WHERE `color_name` = 'Purple';
UPDATE `master_colors` SET `pantone_code` = '14-3812 TCX' WHERE `color_name` = 'Lavender';
UPDATE `master_colors` SET `pantone_code` = '15-5519 TCX' WHERE `color_name` = 'Turquoise';
UPDATE `master_colors` SET `pantone_code` = '17-4421 TCX' WHERE `color_name` = 'Teal';
UPDATE `master_colors` SET `pantone_code` = '13-6111 TCX' WHERE `color_name` = 'Mint';
UPDATE `master_colors` SET `pantone_code` = '11-0105 TCX' WHERE `color_name` = 'Cream';
UPDATE `master_colors` SET `pantone_code` = '11-0107 TCX' WHERE `color_name` = 'Ivory';
UPDATE `master_colors` SET `pantone_code` = '18-1142 TCX' WHERE `color_name` = 'Brown';
UPDATE `master_colors` SET `pantone_code` = '15-1225 TCX' WHERE `color_name` = 'Tan';
UPDATE `master_colors` SET `pantone_code` = '16-1334 TCX' WHERE `color_name` = 'Camel';
UPDATE `master_colors` SET `pantone_code` = '18-6018 TCX' WHERE `color_name` = 'Bottle Green';


-- ============================================================
-- FILE: migration_buyer_po_destinations.sql
-- ============================================================

-- ============================================================
-- Buyer PO Destinations — multi-destination delivery support
-- Follows SAP FMS Buyer PO architecture
-- ============================================================


CREATE TABLE IF NOT EXISTS `buyer_po_destinations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `po_id` int unsigned NOT NULL,
  `destination_name` varchar(255) NOT NULL COMMENT 'Port / city / warehouse',
  `country` varchar(100) DEFAULT NULL,
  `address` text DEFAULT NULL,
  `contact_person` varchar(255) DEFAULT NULL,
  `contact_phone` varchar(50) DEFAULT NULL,
  `contact_email` varchar(255) DEFAULT NULL,
  `quantity` int unsigned NOT NULL DEFAULT 0 COMMENT 'Units allocated to this destination',
  `delivery_date` date DEFAULT NULL,
  `mode_of_shipment` varchar(50) DEFAULT NULL COMMENT 'Sea, Air, Road, Rail',
  `incoterms` varchar(20) DEFAULT NULL COMMENT 'FOB, CIF, DDP, EXW, etc.',
  `status` enum('pending','partially_shipped','shipped','delivered') NOT NULL DEFAULT 'pending',
  `notes` text DEFAULT NULL,
  `display_order` int unsigned NOT NULL DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `po_id` (`po_id`),
  KEY `company_id` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;



-- ============================================================
-- FILE: migration_style_management_new_tabs.sql
-- ============================================================

-- ============================================================
-- New sub-entity tables for Style Management workspace
-- Sizes, Tech Pack, Purchase, Production, QA, Sustainability
-- Also adds designer column to master_styles
-- ============================================================


-- Add designer column to master_styles (ignore if already exists)
-- ALTER TABLE `master_styles` ADD COLUMN `designer` varchar(255) DEFAULT NULL AFTER `product_developer`;

-- Style Sizes (size matrix)
CREATE TABLE IF NOT EXISTS `style_sizes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `size_label` varchar(50) NOT NULL,
  `size_code` varchar(20) DEFAULT NULL COMMENT 'e.g. XS, S, M, L, XL',
  `chest` decimal(8,2) DEFAULT NULL,
  `waist` decimal(8,2) DEFAULT NULL,
  `hip` decimal(8,2) DEFAULT NULL,
  `length` decimal(8,2) DEFAULT NULL,
  `sleeve` decimal(8,2) DEFAULT NULL,
  `shoulder` decimal(8,2) DEFAULT NULL,
  `custom_measurements` json DEFAULT NULL COMMENT 'Additional measurement points as key-value pairs',
  `sku_suffix` varchar(50) DEFAULT NULL COMMENT 'e.g. BLK-M, WHT-L',
  `sequence` int unsigned NOT NULL DEFAULT 0,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Style Tech Pack
CREATE TABLE IF NOT EXISTS `style_tech_pack` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `construction_details` text COMMENT 'Garment construction description',
  `stitch_type` varchar(100) DEFAULT NULL COMMENT 'e.g. 4-Thread Overlock, Flatlock, Coverstitch',
  `stitch_density` varchar(50) DEFAULT NULL COMMENT 'e.g. 10-12 SPI',
  `sewing_instructions` text COMMENT 'Step-by-step sewing instructions',
  `print_placement` text COMMENT 'Print/artwork placement details',
  `embroidery_details` text COMMENT 'Embroidery specifications',
  `wash_instructions` text COMMENT 'Washing/dyeing instructions',
  `care_instructions` text COMMENT 'Care label text',
  `trim_details` text COMMENT 'Labels, hangtags, polybag specs',
  `packing_instructions` text COMMENT 'Folding, tagging, packing method',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Style Purchase Planning
CREATE TABLE IF NOT EXISTS `style_purchase` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `item_name` varchar(255) NOT NULL,
  `item_type` enum('fabric','trim','accessory','packaging','other') NOT NULL DEFAULT 'fabric',
  `supplier` varchar(255) DEFAULT NULL,
  `required_qty` decimal(10,2) NOT NULL DEFAULT 0,
  `required_uom` varchar(20) DEFAULT 'Kg',
  `warehouse_qty` decimal(10,2) DEFAULT 0 COMMENT 'Available in warehouse',
  `reserved_qty` decimal(10,2) DEFAULT 0 COMMENT 'Reserved for other orders',
  `purchase_qty` decimal(10,2) DEFAULT 0 COMMENT 'Qty to purchase = required - warehouse + reserved',
  `lead_time_days` int unsigned DEFAULT NULL,
  `unit_cost` decimal(12,2) DEFAULT NULL,
  `currency_code` varchar(5) DEFAULT 'USD',
  `po_status` enum('not_started','indented','ordered','partial_received','received') NOT NULL DEFAULT 'not_started',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Style Production Planning
CREATE TABLE IF NOT EXISTS `style_production` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `total_smv` decimal(8,2) DEFAULT NULL COMMENT 'Standard Minute Value',
  `total_sam` decimal(8,2) DEFAULT NULL COMMENT 'Standard Allowed Minutes',
  `operators` int unsigned DEFAULT NULL,
  `machines` int unsigned DEFAULT NULL,
  `line_efficiency` decimal(5,2) DEFAULT 65 COMMENT 'Line efficiency percent',
  `daily_capacity` int unsigned DEFAULT NULL COMMENT 'Units per day',
  `estimated_days` int unsigned DEFAULT NULL COMMENT 'Estimated production days',
  `planned_qty` int unsigned DEFAULT NULL,
  `actual_output` int unsigned DEFAULT 0,
  `factory_id` int unsigned DEFAULT NULL,
  `line_id` int unsigned DEFAULT NULL,
  `start_date` date DEFAULT NULL,
  `end_date` date DEFAULT NULL,
  `status` enum('planned','in_progress','completed','on_hold') NOT NULL DEFAULT 'planned',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Style QA / Quality Inspection
CREATE TABLE IF NOT EXISTS `style_qa` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `stage` enum('fabric_inspection','inline','midline','endline','final','packing','shipment') NOT NULL,
  `aql_level` decimal(3,1) DEFAULT 2.5,
  `sample_size` int unsigned DEFAULT NULL,
  `accepted_qty` int unsigned DEFAULT NULL,
  `rejected_qty` int unsigned DEFAULT NULL,
  `defect_list` json DEFAULT NULL COMMENT 'Array of {defect_name, count, severity}',
  `major_defects` int unsigned DEFAULT 0,
  `minor_defects` int unsigned DEFAULT 0,
  `critical_defects` int unsigned DEFAULT 0,
  `result` enum('pass','fail','pending') NOT NULL DEFAULT 'pending',
  `inspector` varchar(255) DEFAULT NULL,
  `inspection_date` date DEFAULT NULL,
  `remarks` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Style Sustainability & Certifications
CREATE TABLE IF NOT EXISTS `style_sustainability` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `certification_name` varchar(255) NOT NULL COMMENT 'OEKO-TEX, GRS, GOTS, BSCI, HIGG, ZDHC, etc.',
  `cert_type` enum('organic','recycled','chemical','social','environmental','other') NOT NULL DEFAULT 'other',
  `status` enum('required','applied','certified','expired','not_required') NOT NULL DEFAULT 'required',
  `certificate_no` varchar(100) DEFAULT NULL,
  `issued_by` varchar(255) DEFAULT NULL,
  `issued_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;



-- ============================================================
-- FILE: migration_tna_fields_to_master_styles.sql
-- ============================================================

-- Add TNA style fields to master_styles for unified Style Development workspace
ALTER TABLE `master_styles`
  ADD COLUMN `description` text DEFAULT NULL AFTER `name`,
  ADD COLUMN `fabric_type` varchar(100) DEFAULT NULL AFTER `category`,
  ADD COLUMN `size_range` varchar(50) DEFAULT NULL AFTER `fabric_type`,
  ADD COLUMN `size_series_id` int unsigned DEFAULT NULL AFTER `size_range`,
  ADD KEY `size_series_id` (`size_series_id`);


-- ============================================================
-- FILE: migration_style_workspace.sql
-- ============================================================

-- ============================================================
-- FashCognitive Style Development + Product Costing Module
-- SAP Fashion Management inspired 360° Style Workspace
-- ============================================================


-- ============================================================
-- 1. Extend master_styles with full style workspace fields
-- ============================================================
ALTER TABLE `master_styles`
  ADD COLUMN `buyer_style_no` varchar(100) DEFAULT NULL AFTER `style_no`,
  ADD COLUMN `brand` varchar(100) DEFAULT NULL AFTER `buyer_style_no`,
  ADD COLUMN `division` varchar(100) DEFAULT NULL AFTER `brand`,
  ADD COLUMN `department` varchar(100) DEFAULT NULL AFTER `division`,
  ADD COLUMN `product_type` varchar(100) DEFAULT NULL AFTER `department`,
  ADD COLUMN `gender` enum('Mens','Womens','Kids','Unisex','Other') DEFAULT NULL AFTER `product_type`,
  ADD COLUMN `season` varchar(50) DEFAULT NULL AFTER `gender`,
  ADD COLUMN `collection` varchar(100) DEFAULT NULL AFTER `season`,
  ADD COLUMN `year` smallint DEFAULT NULL AFTER `collection`,
  ADD COLUMN `factory_id` int unsigned DEFAULT NULL AFTER `year`,
  ADD COLUMN `merchandiser` varchar(255) DEFAULT NULL AFTER `factory_id`,
  ADD COLUMN `product_developer` varchar(255) DEFAULT NULL AFTER `merchandiser`,
  ADD COLUMN `dev_status` enum('development','sampling','approved','production','archived') NOT NULL DEFAULT 'development' AFTER `status`,
  ADD COLUMN `version` varchar(20) DEFAULT 'V1' AFTER `dev_status`,
  ADD COLUMN `fob_target` decimal(12,2) DEFAULT NULL AFTER `version`,
  ADD COLUMN `margin_target` decimal(5,2) DEFAULT NULL AFTER `fob_target`,
  ADD COLUMN `fit` varchar(100) DEFAULT NULL AFTER `margin_target`,
  ADD COLUMN `sleeve` varchar(100) DEFAULT NULL AFTER `fit`,
  ADD COLUMN `construction` varchar(255) DEFAULT NULL AFTER `sleeve`,
  ADD COLUMN `wash` varchar(100) DEFAULT NULL AFTER `construction`,
  ADD COLUMN `print_type` varchar(100) DEFAULT NULL AFTER `wash`,
  ADD COLUMN `embroidery` varchar(255) DEFAULT NULL AFTER `print_type`,
  ADD COLUMN `front_image` varchar(255) DEFAULT NULL AFTER `embroidery`,
  ADD COLUMN `back_image` varchar(255) DEFAULT NULL AFTER `front_image`,
  ADD COLUMN `side_image` varchar(255) DEFAULT NULL AFTER `back_image`,
  ADD COLUMN `model_3d` varchar(255) DEFAULT NULL AFTER `side_image`,
  ADD COLUMN `total_smv` decimal(8,2) DEFAULT NULL AFTER `model_3d`,
  ADD COLUMN `total_material_cost` decimal(12,2) DEFAULT NULL AFTER `total_smv`,
  ADD COLUMN `total_mfg_cost` decimal(12,2) DEFAULT NULL AFTER `total_material_cost`,
  ADD COLUMN `total_overhead` decimal(12,2) DEFAULT NULL AFTER `total_mfg_cost`,
  ADD COLUMN `total_cost` decimal(12,2) DEFAULT NULL AFTER `total_overhead`,
  ADD COLUMN `fob_price` decimal(12,2) DEFAULT NULL AFTER `total_cost`,
  ADD COLUMN `currency_code` varchar(5) DEFAULT 'USD' AFTER `fob_price`,
  ADD COLUMN `approval_status` enum('draft','pending','approved','rejected') NOT NULL DEFAULT 'draft' AFTER `currency_code`,
  ADD COLUMN `approved_by` int unsigned DEFAULT NULL AFTER `approval_status`,
  ADD COLUMN `approved_at` timestamp NULL DEFAULT NULL AFTER `approved_by`,
  ADD KEY `factory_id` (`factory_id`),
  ADD KEY `dev_status` (`dev_status`);

-- ============================================================
-- 2. Style Measurement Points (per size)
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_measurements` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `point_name` varchar(100) NOT NULL COMMENT 'e.g. Chest, Body Length, Sleeve',
  `sequence` int unsigned NOT NULL DEFAULT 0,
  `tolerance` decimal(5,2) DEFAULT NULL,
  `spec_type` enum('buyer','factory','standard') DEFAULT 'buyer',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 3. Style Measurement Values (per point per size)
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_measurement_values` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `measurement_id` int unsigned NOT NULL,
  `size_label` varchar(50) NOT NULL,
  `value` decimal(8,2) NOT NULL DEFAULT 0,
  `revision` int unsigned NOT NULL DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`),
  KEY `measurement_id` (`measurement_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 4. Style Colorways
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_colorways` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `color_name` varchar(100) NOT NULL,
  `pantone` varchar(50) DEFAULT NULL,
  `fabric` varchar(255) DEFAULT NULL,
  `artwork` varchar(255) DEFAULT NULL,
  `trim_color` varchar(100) DEFAULT NULL,
  `image_path` varchar(255) DEFAULT NULL,
  `status` enum('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 5. Style Bill of Materials
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_bom` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `colorway_id` int unsigned DEFAULT NULL,
  `bom_type` enum('fabric','trim','accessory','packaging','other') NOT NULL DEFAULT 'fabric',
  `item_name` varchar(255) NOT NULL,
  `supplier` varchar(255) DEFAULT NULL,
  `gsm` decimal(8,2) DEFAULT NULL,
  `width` decimal(8,2) DEFAULT NULL COMMENT 'inches',
  `consumption` decimal(10,4) NOT NULL DEFAULT 0,
  `consumption_uom` varchar(20) DEFAULT 'Kg' COMMENT 'Kg, Mtr, Pcs, Yds',
  `rate` decimal(12,2) NOT NULL DEFAULT 0,
  `currency_code` varchar(5) DEFAULT 'USD',
  `wastage_pct` decimal(5,2) DEFAULT 0,
  `notes` text,
  `sequence` int unsigned NOT NULL DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`),
  KEY `colorway_id` (`colorway_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 6. Style Consumption Calculator
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_consumption` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `marker_efficiency` decimal(5,2) DEFAULT 85.00 COMMENT 'percent',
  `fabric_width` decimal(8,2) DEFAULT NULL COMMENT 'inches',
  `gsm` decimal(8,2) DEFAULT NULL,
  `fabric_shrinkage` decimal(5,2) DEFAULT 0 COMMENT 'percent',
  `wastage_pct` decimal(5,2) DEFAULT 5 COMMENT 'percent',
  `relaxation_pct` decimal(5,2) DEFAULT 0 COMMENT 'percent',
  `fabric_repeat` decimal(8,2) DEFAULT NULL COMMENT 'inches',
  `matching_allowance` decimal(5,2) DEFAULT 0 COMMENT 'percent',
  `net_consumption` decimal(10,4) DEFAULT NULL,
  `final_consumption` decimal(10,4) DEFAULT NULL,
  `consumption_uom` varchar(20) DEFAULT 'Kg',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 7. Style Operations / Routing (SMV)
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_operations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `operation_name` varchar(255) NOT NULL,
  `machine_type` varchar(100) DEFAULT NULL COMMENT 'Overlock, Flatlock, Single Needle, etc.',
  `smv` decimal(8,2) NOT NULL DEFAULT 0 COMMENT 'Standard Minute Value',
  `sam` decimal(8,2) DEFAULT NULL COMMENT 'Standard Allowed Minutes (= SMV)',
  `operation_type` enum('cutting','sewing','finishing','packing','quality','other') DEFAULT 'sewing',
  `difficulty` enum('easy','medium','hard') DEFAULT 'medium',
  `sequence` int unsigned NOT NULL DEFAULT 0,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 8. Style Costing Header
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_costing` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `version` int unsigned NOT NULL DEFAULT 1,
  `material_cost` decimal(12,2) NOT NULL DEFAULT 0,
  `manufacturing_cost` decimal(12,2) NOT NULL DEFAULT 0,
  `overhead_cost` decimal(12,2) NOT NULL DEFAULT 0,
  `compliance_cost` decimal(12,2) NOT NULL DEFAULT 0,
  `packaging_cost` decimal(12,2) NOT NULL DEFAULT 0,
  `total_cost` decimal(12,2) NOT NULL DEFAULT 0,
  `margin_pct` decimal(5,2) DEFAULT 0,
  `fob_price` decimal(12,2) DEFAULT 0,
  `currency_code` varchar(5) DEFAULT 'USD',
  `status` enum('draft','final') NOT NULL DEFAULT 'draft',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 9. Style Cost Components (detailed line items)
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_cost_components` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `costing_id` int unsigned NOT NULL,
  `category` enum('material','manufacturing','overhead','compliance','packaging') NOT NULL,
  `item_name` varchar(255) NOT NULL,
  `cost` decimal(12,2) NOT NULL DEFAULT 0,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`),
  KEY `costing_id` (`costing_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 10. Style Packaging
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_packaging` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `item_name` varchar(255) NOT NULL,
  `quantity` decimal(10,4) NOT NULL DEFAULT 1,
  `rate` decimal(12,2) NOT NULL DEFAULT 0,
  `uom` varchar(20) DEFAULT 'Pcs',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 11. Style Compliance
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_compliance` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `category` enum('testing','audit','sustainability','certification','other') NOT NULL,
  `item_name` varchar(255) NOT NULL,
  `cost` decimal(12,2) NOT NULL DEFAULT 0,
  `required` tinyint(1) NOT NULL DEFAULT 1,
  `status` enum('pending','in_progress','completed','not_required') NOT NULL DEFAULT 'pending',
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 12. Style Documents
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_documents` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `doc_type` enum('tech_pack','spec_sheet','image','3d_model','pdf','excel','other') NOT NULL DEFAULT 'other',
  `doc_name` varchar(255) NOT NULL,
  `file_path` varchar(500) NOT NULL,
  `uploaded_by` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 13. Style AI Analysis
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_ai_analysis` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `analysis_type` enum('cost_optimization','supplier_alternative','risk_assessment','profitability','consumption','other') NOT NULL,
  `summary` text,
  `recommendation` text,
  `potential_saving` decimal(12,2) DEFAULT NULL,
  `risk_level` enum('low','medium','high') DEFAULT 'low',
  `confidence` decimal(5,2) DEFAULT NULL COMMENT '0-100',
  `raw_data` json DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 14. Style Approvals
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_approvals` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `approval_level` int unsigned NOT NULL DEFAULT 1,
  `role_name` varchar(100) NOT NULL COMMENT 'Product Developer, Merchandiser, Costing Manager, etc.',
  `user_id` int unsigned DEFAULT NULL,
  `status` enum('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  `remarks` text,
  `acted_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ============================================================
-- 15. Style Versions (version history)
-- ============================================================
CREATE TABLE IF NOT EXISTS `style_versions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `style_id` int unsigned NOT NULL,
  `version_label` varchar(20) NOT NULL COMMENT 'V1, V2, V3...',
  `change_description` text,
  `changed_by` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `style_id` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;



-- ============================================================
-- FILE: seed_style_dummy_data.sql
-- ============================================================

-- ============================================================
-- SEED DUMMY DATA FOR ALL STYLE SUB-ENTITIES (20 tables × 9 styles)
-- ============================================================

-- Clear existing sub-entity data
TRUNCATE TABLE style_measurement_values;
TRUNCATE TABLE style_measurements;
TRUNCATE TABLE style_colorways;
TRUNCATE TABLE style_bom;
TRUNCATE TABLE style_consumption;
TRUNCATE TABLE style_operations;
TRUNCATE TABLE style_cost_components;
TRUNCATE TABLE style_costing;
TRUNCATE TABLE style_packaging;
TRUNCATE TABLE style_compliance;
TRUNCATE TABLE style_documents;
TRUNCATE TABLE style_ai_analysis;
TRUNCATE TABLE style_approvals;
TRUNCATE TABLE style_versions;
TRUNCATE TABLE style_sizes;
TRUNCATE TABLE style_tech_pack;
TRUNCATE TABLE style_purchase;
TRUNCATE TABLE style_production;
TRUNCATE TABLE style_qa;
TRUNCATE TABLE style_sustainability;

-- ============================================================
-- 1. STYLE_MEASUREMENTS — Measurement point definitions
-- ============================================================
INSERT INTO style_measurements (company_id, style_id, point_name, sequence, tolerance, spec_type) VALUES
-- T-Shirt (1)
(1,1,'Chest Width',1,0.50,'buyer'),(1,1,'Body Length',2,0.50,'buyer'),(1,1,'Sleeve Length',3,0.25,'buyer'),(1,1,'Shoulder Width',4,0.25,'buyer'),(1,1,'Neck Opening',5,0.25,'buyer'),(1,1,'Hem Width',6,0.50,'buyer'),
-- Chino Pants (2)
(1,2,'Waist',1,0.50,'buyer'),(1,2,'Hip',2,0.50,'buyer'),(1,2,'Inseam',3,0.50,'buyer'),(1,2,'Outseam',4,0.50,'buyer'),(1,2,'Thigh',5,0.25,'buyer'),(1,2,'Knee',6,0.25,'buyer'),(1,2,'Leg Opening',7,0.25,'buyer'),
-- Blazer (3)
(1,3,'Chest',1,0.50,'buyer'),(1,3,'Shoulder',2,0.25,'buyer'),(1,3,'Sleeve Length',3,0.25,'buyer'),(1,3,'Back Length',4,0.50,'buyer'),(1,3,'Waist',5,0.50,'buyer'),(1,3,'Neck Drop',6,0.25,'buyer'),
-- Sweater (4)
(1,4,'Chest',1,0.50,'buyer'),(1,4,'Length',2,0.50,'buyer'),(1,4,'Sleeve',3,0.25,'buyer'),(1,4,'Shoulder',4,0.25,'buyer'),(1,4,'Hem',5,0.50,'buyer'),
-- Running Shorts (5)
(1,5,'Waist',1,0.50,'buyer'),(1,5,'Hip',2,0.50,'buyer'),(1,5,'Inseam',3,0.25,'buyer'),(1,5,'Outseam',4,0.50,'buyer'),(1,5,'Leg Opening',5,0.25,'buyer'),
-- Hoodie (6)
(1,6,'Chest',1,0.50,'buyer'),(1,6,'Body Length',2,0.50,'buyer'),(1,6,'Sleeve Length',3,0.25,'buyer'),(1,6,'Shoulder',4,0.25,'buyer'),(1,6,'Hood Height',5,0.25,'buyer'),(1,6,'Pocket Width',6,0.50,'buyer'),
-- Running Tights (7)
(1,7,'Waist',1,0.50,'buyer'),(1,7,'Hip',2,0.50,'buyer'),(1,7,'Inseam',3,0.25,'buyer'),(1,7,'Thigh',4,0.25,'buyer'),(1,7,'Knee',5,0.25,'buyer'),(1,7,'Ankle Opening',6,0.25,'buyer'),
-- Base Layer (8)
(1,8,'Chest',1,0.50,'buyer'),(1,8,'Body Length',2,0.50,'buyer'),(1,8,'Sleeve Length',3,0.25,'buyer'),(1,8,'Shoulder',4,0.25,'buyer'),(1,8,'Neck Opening',5,0.25,'buyer'),
-- Denim Jacket (9)
(1,9,'Chest',1,0.50,'buyer'),(1,9,'Shoulder',2,0.25,'buyer'),(1,9,'Sleeve Length',3,0.25,'buyer'),(1,9,'Back Length',4,0.50,'buyer'),(1,9,'Waist',5,0.50,'buyer'),(1,9,'Neck Drop',6,0.25,'buyer');

-- ============================================================
-- 2. STYLE_MEASUREMENT_VALUES — Values per size
-- ============================================================
INSERT INTO style_measurement_values (company_id, style_id, measurement_id, size_label, value, revision) VALUES
-- T-Shirt measurements (id 1-6)
(1,1,1,'S',48.00,1),(1,1,1,'M',52.00,1),(1,1,1,'L',56.00,1),(1,1,1,'XL',60.00,1),(1,1,1,'XXL',64.00,1),
(1,1,2,'S',68.00,1),(1,1,2,'M',70.00,1),(1,1,2,'L',72.00,1),(1,1,2,'XL',74.00,1),(1,1,2,'XXL',76.00,1),
(1,1,3,'S',20.00,1),(1,1,3,'M',21.00,1),(1,1,3,'L',22.00,1),(1,1,3,'XL',23.00,1),(1,1,3,'XXL',24.00,1),
(1,1,4,'S',40.00,1),(1,1,4,'M',42.00,1),(1,1,4,'L',44.00,1),(1,1,4,'XL',46.00,1),(1,1,4,'XXL',48.00,1),
(1,1,5,'S',19.00,1),(1,1,5,'M',20.00,1),(1,1,5,'L',21.00,1),(1,1,5,'XL',22.00,1),(1,1,5,'XXL',23.00,1),
(1,1,6,'S',46.00,1),(1,1,6,'M',50.00,1),(1,1,6,'L',54.00,1),(1,1,6,'XL',58.00,1),(1,1,6,'XXL',62.00,1),
-- Chino Pants measurements (id 7-13)
(1,2,7,'30',76.00,1),(1,2,7,'32',81.00,1),(1,2,7,'34',86.00,1),(1,2,7,'36',91.00,1),
(1,2,8,'30',96.00,1),(1,2,8,'32',101.00,1),(1,2,8,'34',106.00,1),(1,2,8,'36',111.00,1),
(1,2,9,'30',78.00,1),(1,2,9,'32',78.00,1),(1,2,9,'34',78.00,1),(1,2,9,'36',78.00,1),
(1,2,10,'30',104.00,1),(1,2,10,'32',106.00,1),(1,2,10,'34',108.00,1),(1,2,10,'36',110.00,1),
(1,2,11,'30',28.00,1),(1,2,11,'32',29.50,1),(1,2,11,'34',31.00,1),(1,2,11,'36',32.50,1),
(1,2,12,'30',20.00,1),(1,2,12,'32',21.00,1),(1,2,12,'34',22.00,1),(1,2,12,'36',23.00,1),
(1,2,13,'30',16.00,1),(1,2,13,'32',17.00,1),(1,2,13,'34',18.00,1),(1,2,13,'36',19.00,1),
-- Blazer measurements (id 14-19)
(1,3,14,'S',96.00,1),(1,3,14,'M',102.00,1),(1,3,14,'L',108.00,1),(1,3,14,'XL',114.00,1),
(1,3,15,'S',42.00,1),(1,3,15,'M',44.00,1),(1,3,15,'L',46.00,1),(1,3,15,'XL',48.00,1),
(1,3,16,'S',63.00,1),(1,3,16,'M',64.50,1),(1,3,16,'L',66.00,1),(1,3,16,'XL',67.50,1),
(1,3,17,'S',68.00,1),(1,3,17,'M',70.00,1),(1,3,17,'L',72.00,1),(1,3,17,'XL',74.00,1),
(1,3,18,'S',88.00,1),(1,3,18,'M',94.00,1),(1,3,18,'L',100.00,1),(1,3,18,'XL',106.00,1),
(1,3,19,'S',22.00,1),(1,3,19,'M',23.00,1),(1,3,19,'L',24.00,1),(1,3,19,'XL',25.00,1);

-- ============================================================
-- 3. STYLE_COLORWAYS — Color variants
-- ============================================================
INSERT INTO style_colorways (company_id, style_id, color_name, pantone, fabric, trim_color, status) VALUES
(1,1,'White','PMS 11-0601','100% Cotton Jersey','White','approved'),
(1,1,'Black','PMS 19-4007','100% Cotton Jersey','Black','approved'),
(1,1,'Navy','PMS 19-4024','100% Cotton Jersey','Navy','approved'),
(1,1,'Heather Grey','PMS 14-4102','Cotton/Poly Blend','Grey','pending'),
(1,2,'Khaki','PMS 15-1214','98% Cotton 2% Elastane','Khaki','approved'),
(1,2,'Charcoal','PMS 19-3906','98% Cotton 2% Elastane','Charcoal','approved'),
(1,2,'Olive','PMS 18-0527','98% Cotton 2% Elastane','Olive','approved'),
(1,3,'Charcoal','PMS 19-3906','Wool/Poly Blend','Black','approved'),
(1,3,'Navy','PMS 19-4024','Wool/Poly Blend','Navy','approved'),
(1,3,'Slate Grey','PMS 17-4014','Wool/Poly Blend','Grey','pending'),
(1,4,'Camel','PMS 15-1225','100% Cashmere','Camel','approved'),
(1,4,'Black','PMS 19-4007','100% Cashmere','Black','approved'),
(1,4,'Burgundy','PMS 19-1535','100% Cashmere','Burgundy','approved'),
(1,5,'Black','PMS 19-4007','Dri-FIT Polyester','Black','approved'),
(1,5,'Blue','PMS 19-4052','Dri-FIT Polyester','Blue','approved'),
(1,5,'Red','PMS 18-1763','Dri-FIT Polyester','Red','approved'),
(1,6,'Black','PMS 19-4007','Fleece Cotton/Poly','Black','approved'),
(1,6,'Grey','PMS 14-4102','Fleece Cotton/Poly','Grey','approved'),
(1,6,'Red','PMS 18-1763','Fleece Cotton/Poly','Red','pending'),
(1,7,'Black','PMS 19-4007','Spandex/Polyester','Black','approved'),
(1,7,'Navy','PMS 19-4024','Spandex/Polyester','Navy','approved'),
(1,8,'Black','PMS 19-4007','HeatTech Synthetic','Black','approved'),
(1,8,'White','PMS 11-0601','HeatTech Synthetic','White','approved'),
(1,9,'Indigo','PMS 19-3939','12oz Denim','Copper','approved'),
(1,9,'Black Denim','PMS 19-4007','12oz Denim','Gunmetal','approved'),
(1,9,'Washed Blue','PMS 17-4028','10oz Denim','Antique Brass','approved');

-- ============================================================
-- 4. STYLE_BOM — Bill of Materials
-- ============================================================
INSERT INTO style_bom (company_id, style_id, bom_type, item_name, supplier, gsm, width, consumption, consumption_uom, rate, currency_code, wastage_pct, notes, sequence) VALUES
-- T-Shirt (1)
(1,1,'fabric','100% Combed Cotton Jersey 180gsm','FabricMart',180.00,160.00,1.2000,'Kg',4.50,'USD',5.00,'Main body fabric',1),
(1,1,'trim','Rib Neck Collar 1x1','TrimCo',220.00,NULL,0.1500,'Kg',8.00,'USD',3.00,'Match body color',2),
(1,1,'trim','Shoulder Tape 15mm','TrimCo',NULL,NULL,0.0500,'Kg',2.50,'USD',2.00,'Cotton twill tape',3),
(1,1,'accessory','Woven Label 30x50mm','LabelPro',NULL,NULL,1.0000,'Pcs',0.12,'USD',0.00,'Main brand label',4),
(1,1,'accessory','Care Label SAT-001','LabelPro',NULL,NULL,1.0000,'Pcs',0.08,'USD',0.00,'Care instructions',5),
(1,1,'packaging','Polybag 30x40cm','PackAll',NULL,NULL,1.0000,'Pcs',0.03,'USD',0.00,'Individual packing',6),
(1,1,'packaging','Carton Box 60x40x40cm','PackAll',NULL,NULL,0.0625,'Pcs',0.85,'USD',0.00,'16 pcs per carton',7),
-- Chino Pants (2)
(1,2,'fabric','Cotton Twill 98/2 Elastane 230gsm','TextilePro',230.00,150.00,1.3500,'Kg',5.80,'USD',7.00,'Main body fabric',1),
(1,2,'trim','YKK Zipper #5 18cm','YKK',NULL,NULL,1.0000,'Pcs',0.45,'USD',0.00,'Front fly',2),
(1,2,'trim','Belt Loop Webbing 40mm','TrimCo',NULL,NULL,0.0200,'Kg',3.20,'USD',5.00,'7 belt loops per pant',3),
(1,2,'accessory','Metal Shank Button 17mm','ButtonCraft',NULL,NULL,1.0000,'Pcs',0.15,'USD',0.00,'Waistband closure',4),
(1,2,'accessory','Woven Main Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.14,'USD',0.00,'Brand label',5),
(1,2,'accessory','Size Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.05,'USD',0.00,'Size tag',6),
(1,2,'packaging','Tissue Paper','PackAll',NULL,NULL,1.0000,'Pcs',0.06,'USD',0.00,'Individual fold',7),
(1,2,'packaging','Polybag 35x50cm','PackAll',NULL,NULL,1.0000,'Pcs',0.04,'USD',0.00,'Outer bag',8),
-- Blazer (3)
(1,3,'fabric','Wool/Poly Blend 280gsm','LuxTextiles',280.00,150.00,1.8000,'Kg',12.50,'USD',10.00,'Shell fabric',1),
(1,3,'fabric','Polyester Lining 110gsm','LuxTextiles',110.00,140.00,0.9000,'Kg',3.20,'USD',5.00,'Full lining',2),
(1,3,'trim','Shoulder Pad Set','AccessoryHub',NULL,NULL,1.0000,'Set',1.80,'USD',0.00,'Semi-rigid',3),
(1,3,'trim','Fusible Interlining','InterlineCo',NULL,NULL,0.4000,'Kg',6.50,'USD',3.00,'Front panels + collar',4),
(1,3,'accessory','Horn Buttons 20mm','ButtonCraft',NULL,NULL,8.0000,'Pcs',0.35,'USD',0.00,'Front + cuffs',5),
(1,3,'accessory','Inner Pocket Woven Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.18,'USD',0.00,'Brand badge',6),
(1,3,'accessory','Hanging Loop Ribbon','TrimCo',NULL,NULL,0.1000,'Kg',4.00,'USD',0.00,'Neck loop',7),
(1,3,'packaging','Suit Cover Non-Woven','PackAll',NULL,NULL,1.0000,'Pcs',0.65,'USD',0.00,'Individual cover',8),
-- Sweater (4)
(1,4,'fabric','100% Cashmere 12gg Knit','CashMill',NULL,NULL,0.4500,'Kg',38.00,'USD',8.00,'12-gauge knit',1),
(1,4,'trim','Rib Trim 2x2 1x1','KnitTrims',NULL,NULL,0.0800,'Kg',15.00,'USD',3.00,'Cuffs and hem',2),
(1,4,'accessory','Woven Main Label 30x60mm','LabelPro',NULL,NULL,1.0000,'Pcs',0.22,'USD',0.00,'Brand label',3),
(1,4,'accessory','Care Label SAT-002','LabelPro',NULL,NULL,1.0000,'Pcs',0.10,'USD',0.00,'Hand wash only',4),
(1,4,'packaging','Tissue Paper','PackAll',NULL,NULL,2.0000,'Pcs',0.08,'USD',0.00,'Double fold',5),
(1,4,'packaging','Rigid Gift Box','PackAll',NULL,NULL,1.0000,'Pcs',1.20,'USD',0.00,'Premium packaging',6),
-- Running Shorts (5)
(1,5,'fabric','Dri-FIT Polyester 130gsm','NikeFab',130.00,150.00,0.4500,'Kg',3.80,'USD',5.00,'Moisture wicking',1),
(1,5,'fabric','Mesh Lining 80gsm','NikeFab',80.00,150.00,0.2500,'Kg',2.50,'USD',3.00,'Inner brief',2),
(1,5,'trim','Elastic Waistband 35mm','ElasticCo',NULL,NULL,0.8500,'M',0.18,'USD',5.00,'Drawcord channel',3),
(1,5,'trim','Drawcord 5mm','TrimCo',NULL,NULL,1.0000,'M',0.06,'USD',0.00,'Adjustable waist',4),
(1,5,'accessory','Reflective Heat Transfer','PrintTech',NULL,NULL,1.0000,'Pcs',0.25,'USD',0.00,'Logo placement',5),
(1,5,'accessory','Woven Label 25x40mm','LabelPro',NULL,NULL,1.0000,'Pcs',0.10,'USD',0.00,'Brand tag',6),
(1,5,'packaging','Polybag 25x35cm','PackAll',NULL,NULL,1.0000,'Pcs',0.02,'USD',0.00,'Individual packing',7),
-- Hoodie (6)
(1,6,'fabric','Cotton/Poly Fleece 320gsm','FleeceMill',320.00,160.00,1.6000,'Kg',5.50,'USD',7.00,'Brushed fleece',1),
(1,6,'trim','Kangaroo Pocket Rib','KnitTrims',NULL,NULL,0.1200,'Kg',6.00,'USD',3.00,'Pocket opening trim',2),
(1,6,'trim','Hood Drawcord 6mm','TrimCo',NULL,NULL,1.2000,'M',0.08,'USD',0.00,'Flat cord',3),
(1,6,'accessory','Metal Eyelets 5mm', 'AccessoryHub',NULL,NULL,2.0000,'Pcs',0.04,'USD',0.00,'Hood drawcord holes',4),
(1,6,'accessory','Woven Main Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.14,'USD',0.00,'Brand label',5),
(1,6,'accessory','Size Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.05,'USD',0.00,'Size tag',6),
(1,6,'packaging','Polybag 40x55cm','PackAll',NULL,NULL,1.0000,'Pcs',0.05,'USD',0.00,'Individual packing',7),
(1,6,'packaging','Carton Box 60x40x40cm','PackAll',NULL,NULL,0.0625,'Pcs',0.85,'USD',0.00,'12 pcs per carton',8),
-- Running Tights (7)
(1,7,'fabric','Spandex/Polyester 200gsm','PerformanceKnit',200.00,150.00,0.5500,'Kg',6.20,'USD',5.00,'4-way stretch',1),
(1,7,'trim','Elastic Waistband 30mm','ElasticCo',NULL,NULL,0.8000,'M',0.22,'USD',5.00,'Wide comfort band',2),
(1,7,'accessory','Flatlock Stitch Reinforcement','ThreadCo',NULL,NULL,1.0000,'Pcs',0.15,'USD',0.00,'Seam durability',3),
(1,7,'accessory','Reflective Print','PrintTech',NULL,NULL,1.0000,'Pcs',0.30,'USD',0.00,'Low-light visibility',4),
(1,7,'accessory','Woven Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.10,'USD',0.00,'Brand tag',5),
(1,7,'packaging','Polybag 25x40cm','PackAll',NULL,NULL,1.0000,'Pcs',0.03,'USD',0.00,'Individual packing',6),
-- Base Layer (8)
(1,8,'fabric','HeatTech Synthetic 140gsm','UltraWarm',140.00,160.00,0.4000,'Kg',4.80,'USD',4.00,'Heat retention fabric',1),
(1,8,'trim','Flat Lock Seam Thread','ThreadCo',NULL,NULL,0.0200,'Kg',12.00,'USD',2.00,'Seamless comfort',2),
(1,8,'accessory','Heat Seal Label','PrintTech',NULL,NULL,1.0000,'Pcs',0.08,'USD',0.00,'No-tag comfort',3),
(1,8,'accessory','Woven Size Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.05,'USD',0.00,'Size indicator',4),
(1,8,'packaging','Polybag 20x30cm','PackAll',NULL,NULL,1.0000,'Pcs',0.02,'USD',0.00,'Compact packing',5),
-- Denim Jacket (9)
(1,9,'fabric','12oz Raw Denim','DenimWorks',NULL,NULL,1.8000,'Kg',7.50,'USD',8.00,'Ring spun indigo',1),
(1,9,'fabric','Cotton/Poly Lining 90gsm','FabricMart',90.00,140.00,0.6000,'Kg',2.80,'USD',5.00,'Body lining',2),
(1,9,'trim','YKK Brass Zipper #8','YKK',NULL,NULL,1.0000,'Pcs',1.20,'USD',0.00,'Front closure',3),
(1,9,'trim','Copper Rivets','AccessoryHub',NULL,NULL,12.0000,'Pcs',0.06,'USD',0.00,'Stress points',4),
(1,9,'accessory','Woven Main Label','LabelPro',NULL,NULL,1.0000,'Pcs',0.14,'USD',0.00,'Brand label',5),
(1,9,'accessory','Leather Patch 50x70mm','AccessoryHub',NULL,NULL,1.0000,'Pcs',0.45,'USD',0.00,'Back neck patch',6),
(1,9,'accessory','Shank Button 17mm','ButtonCraft',NULL,NULL,4.0000,'Pcs',0.18,'USD',0.00,'Cuff buttons',7),
(1,9,'packaging','Butcher Paper Wrap','PackAll',NULL,NULL,1.0000,'Pcs',0.12,'USD',0.00,'Individual wrap',8),
(1,9,'packaging','Carton Box 60x40x40cm','PackAll',NULL,NULL,0.05,'Pcs',0.85,'USD',0.00,'10 pcs per carton',9);

-- ============================================================
-- 5. STYLE_CONSUMPTION — Fabric consumption details
-- ============================================================
INSERT INTO style_consumption (company_id, style_id, marker_efficiency, fabric_width, gsm, fabric_shrinkage, wastage_pct, relaxation_pct, net_consumption, final_consumption, consumption_uom, notes) VALUES
(1,1, 85.00,160.00,180.00,3.00,5.00,1.00,1.1500,1.2075,'Kg','T-shirt marker'),
(1,2, 82.00,150.00,230.00,2.00,7.00,0.50,1.2800,1.3696,'Kg','Chino trouser marker'),
(1,3, 78.00,150.00,280.00,2.00,10.00,1.00,1.6200,1.7820,'Kg','Blazer marker — complex layout'),
(1,4, NULL, NULL, NULL, 0.00,8.00,2.00,0.4200,0.4536,'Kg','Knit consumption — no marker needed'),
(1,5, 88.00,150.00,130.00,1.50,5.00,0.50,0.4200,0.4410,'Kg','Shorts marker'),
(1,6, 80.00,160.00,320.00,3.00,7.00,1.50,1.4800,1.5984,'Kg','Hoodie marker — includes hood'),
(1,7, 90.00,150.00,200.00,1.00,5.00,0.50,0.5100,0.5355,'Kg','Tights marker — tubular'),
(1,8, NULL, NULL, NULL, 0.00,4.00,1.00,0.3800,0.3952,'Kg','Seamless knit — flat consumption'),
(1,9, 78.00,150.00, NULL, 3.00,8.00,1.50,1.6500,1.7820,'Kg','Denim jacket marker — complex');

-- ============================================================
-- 6. STYLE_OPERATIONS — Manufacturing operations
-- ============================================================
INSERT INTO style_operations (company_id, style_id, operation_name, machine_type, smv, sam, operation_type, difficulty, sequence, notes) VALUES
-- T-Shirt (1)
(1,1,'Front Panel Cut','Straight Knife',0.80,0.80,'cutting','easy',1,'Single jersey fabric'),
(1,1,'Back Panel Cut','Straight Knife',0.70,0.70,'cutting','easy',2,NULL),
(1,1,'Sleeve Cut','Straight Knife',0.50,0.50,'cutting','easy',3,NULL),
(1,1,'Shoulder Seam','Overlock 5-thread',0.45,0.45,'sewing','easy',4,NULL),
(1,1,'Neck Collar Attach','Coverstitch',0.60,0.60,'sewing','medium',5,'Rib collar binding'),
(1,1,'Sleeve Set-in','Overlock 5-thread',0.75,0.75,'sewing','medium',6,NULL),
(1,1,'Side Seam','Overlock 5-thread',0.55,0.55,'sewing','easy',7,NULL),
(1,1,'Hem Bottom','Coverstitch',0.40,0.40,'sewing','easy',8,NULL),
(1,1,'Sleeve Hem','Coverstitch',0.35,0.35,'sewing','easy',9,NULL),
(1,1,'Label Attach','Single Needle',0.20,0.20,'sewing','easy',10,NULL),
(1,1,'Trim & Thread Cut','Manual',0.30,0.30,'finishing','easy',11,NULL),
(1,1,'Quality Check','Manual',0.40,0.40,'quality','medium',12,'100% inline check'),
(1,1,'Fold & Polybag','Manual',0.25,0.25,'packing','easy',13,NULL),
-- Chino Pants (2)
(1,2,'Front Panel Cut','Straight Knife',1.20,1.20,'cutting','medium',1,'Twill fabric — multiple pieces'),
(1,2,'Back Panel Cut','Straight Knife',1.00,1.00,'cutting','medium',2,NULL),
(1,2,'Pocket Bag Cut','Straight Knife',0.40,0.40,'cutting','easy',3,'Pocketing fabric'),
(1,2,'Front Dart & Pleat','Single Needle',0.60,0.60,'sewing','medium',4,NULL),
(1,2,'Back Welt Pocket','Single Needle',1.20,1.20,'sewing','hard',5,'Double welt pocket'),
(1,2,'Front Pocket Attach','Single Needle',0.80,0.80,'sewing','medium',6,NULL),
(1,2,'Fly Zipper Attach','Single Needle',0.90,0.90,'sewing','medium',7,NULL),
(1,2,'Inseam','Overlock 5-thread',0.65,0.65,'sewing','easy',8,NULL),
(1,2,'Outseam','Overlock 5-thread',0.65,0.65,'sewing','easy',9,NULL),
(1,2,'Waistband Attach','Lockstitch',0.85,0.85,'sewing','medium',10,NULL),
(1,2,'Belt Loop Attach','Bartack',0.50,0.50,'sewing','medium',11,'7 loops'),
(1,2,'Hem','Coverstitch',0.35,0.35,'sewing','easy',12,NULL),
(1,2,'Buttonhole & Button','Buttonhole M/C',0.40,0.40,'sewing','medium',13,NULL),
(1,2,'Quality Check','Manual',0.50,0.50,'quality','medium',14,NULL),
(1,2,'Press & Fold','Steam Press',0.45,0.45,'finishing','medium',15,NULL),
(1,2,'Polybag & Tag','Manual',0.30,0.30,'packing','easy',16,NULL),
-- Blazer (3)
(1,3,'Front Panel Cut','Straight Knife',1.50,1.50,'cutting','hard',1,'Complex pattern pieces'),
(1,3,'Back Panel Cut','Straight Knife',1.00,1.00,'cutting','medium',2,NULL),
(1,3,'Lining Cut','Straight Knife',0.80,0.80,'cutting','medium',3,NULL),
(1,3,'Fusing Press','Fusing Machine',1.20,1.20,'finishing','medium',4,'Front + collar interlining'),
(1,3,'Dart & Princess Seam','Single Needle',1.40,1.40,'sewing','hard',5,NULL),
(1,3,'Back Vent','Single Needle',0.80,0.80,'sewing','medium',6,NULL),
(1,3,'Collar Make','Single Needle',1.80,1.80,'sewing','hard',7,'Notch collar construction'),
(1,3,'Lining Attach','Single Needle',2.00,2.00,'sewing','hard',8,'Full lining'),
(1,3,'Sleeve Set-in','Overlock',1.20,1.20,'sewing','hard',9,NULL),
(1,3,'Buttonhole','Buttonhole M/C',0.60,0.60,'sewing','medium',10,'5 buttonholes'),
(1,3,'Button Attach','Manual',0.50,0.50,'sewing','medium',11,'5 buttons'),
(1,3,'Shoulder Pad Attach','Manual',0.40,0.40,'sewing','medium',12,NULL),
(1,3,'Press & Shape','Steam Press',1.00,1.00,'finishing','hard',13,'Critical finishing'),
(1,3,'Quality Check','Manual',0.80,0.80,'quality','hard',14,'Detailed QC'),
(1,3,'Hang & Cover','Manual',0.35,0.35,'packing','easy',15,NULL),
-- Sweater (4)
(1,4,'Front Panel Knit','Flat Knit M/C',8.00,8.00,'cutting','medium',1,'12-gauge flat knit'),
(1,4,'Back Panel Knit','Flat Knit M/C',8.00,8.00,'cutting','medium',2,NULL),
(1,4,'Sleeve Knit','Flat Knit M/C',5.00,5.00,'cutting','easy',3,NULL),
(1,4,'Linking — Shoulder','Linking M/C',1.50,1.50,'sewing','hard',4,'Wholegarment linking'),
(1,4,'Linking — Sleeve','Linking M/C',1.20,1.20,'sewing','medium',5,NULL),
(1,4,'Collar Rib Attach','Linking M/C',0.80,0.80,'sewing','medium',6,NULL),
(1,4,'Hem Rib Attach','Linking M/C',0.70,0.70,'sewing','medium',7,NULL),
(1,4,'Cuff Rib Attach','Linking M/C',0.50,0.50,'sewing','easy',8,NULL),
(1,4,'Label Sew','Single Needle',0.20,0.20,'sewing','easy',9,NULL),
(1,4,'Wash & Block','Wash M/C',0.00,0.00,'finishing','medium',10,'Cashmere wash'),
(1,4,'Quality Check','Manual',0.50,0.50,'quality','medium',11,NULL),
(1,4,'Fold & Box','Manual',0.40,0.40,'packing','easy',12,'Premium box packing'),
-- Running Shorts (5)
(1,5,'Main Panel Cut','Straight Knife',0.60,0.60,'cutting','easy',1,'Light fabric'),
(1,5,'Lining Cut','Straight Knife',0.30,0.30,'cutting','easy',2,NULL),
(1,5,'Side Seam','Overlock',0.40,0.40,'sewing','easy',3,NULL),
(1,5,'Inseam','Overlock',0.35,0.35,'sewing','easy',4,NULL),
(1,5,'Waistband Channel','Lockstitch',0.50,0.50,'sewing','medium',5,'Drawcord channel'),
(1,5,'Drawcord Thread','Manual',0.15,0.15,'sewing','easy',6,NULL),
(1,5,'Lining Attach','Overlock',0.30,0.30,'sewing','easy',7,NULL),
(1,5,'Reflective Transfer','Heat Press',0.20,0.20,'finishing','easy',8,NULL),
(1,5,'Hem','Coverstitch',0.25,0.25,'sewing','easy',9,NULL),
(1,5,'Label Attach','Single Needle',0.15,0.15,'sewing','easy',10,NULL),
(1,5,'Quality Check','Manual',0.30,0.30,'quality','medium',11,NULL),
(1,5,'Fold & Polybag','Manual',0.20,0.20,'packing','easy',12,NULL),
-- Hoodie (6)
(1,6,'Front Panel Cut','Straight Knife',1.10,1.10,'cutting','medium',1,'Fleece fabric'),
(1,6,'Back Panel Cut','Straight Knife',0.90,0.90,'cutting','medium',2,NULL),
(1,6,'Hood Cut','Straight Knife',0.40,0.40,'cutting','easy',3,NULL),
(1,6,'Pocket Cut','Straight Knife',0.35,0.35,'cutting','easy',4,NULL),
(1,6,'Sleeve Cut','Straight Knife',0.50,0.50,'cutting','easy',5,NULL),
(1,6,'Kangaroo Pocket Sew','Single Needle',0.80,0.80,'sewing','medium',6,NULL),
(1,6,'Hood Construct','Overlock',0.70,0.70,'sewing','medium',7,NULL),
(1,6,'Shoulder Seam','Overlock',0.50,0.50,'sewing','easy',8,NULL),
(1,6,'Hood Attach','Overlock',0.65,0.65,'sewing','medium',9,NULL),
(1,6,'Sleeve Set-in','Overlock',0.80,0.80,'sewing','medium',10,NULL),
(1,6,'Side Seam + Pocket','Overlock',0.70,0.70,'sewing','medium',11,NULL),
(1,6,'Waistband Rib','Coverstitch',0.45,0.45,'sewing','medium',12,NULL),
(1,6,'Cuff Rib','Coverstitch',0.35,0.35,'sewing','easy',13,NULL),
(1,6,'Drawcord Thread + Eyelet','Manual',0.30,0.30,'sewing','medium',14,NULL),
(1,6,'Label Attach','Single Needle',0.20,0.20,'sewing','easy',15,NULL),
(1,6,'Quality Check','Manual',0.45,0.45,'quality','medium',16,NULL),
(1,6,'Fold & Polybag','Manual',0.30,0.30,'packing','easy',17,NULL),
-- Running Tights (7)
(1,7,'Main Panel Cut','Straight Knife',0.70,0.70,'cutting','easy',1,'Stretch fabric'),
(1,7,'Gusset Cut','Straight Knife',0.20,0.20,'cutting','easy',2,NULL),
(1,7,'Inseam Flatlock','Flatlock M/C',0.60,0.60,'sewing','medium',3,'Flatlock seam'),
(1,7,'Outseam Flatlock','Flatlock M/C',0.60,0.60,'sewing','medium',4,NULL),
(1,7,'Gusset Attach','Flatlock M/C',0.35,0.35,'sewing','medium',5,NULL),
(1,7,'Waistband Attach','Coverstitch',0.50,0.50,'sewing','medium',6,NULL),
(1,7,'Reflective Print','Heat Press',0.25,0.25,'finishing','easy',7,NULL),
(1,7,'Label Attach','Single Needle',0.15,0.15,'sewing','easy',8,NULL),
(1,7,'Quality Check','Manual',0.35,0.35,'quality','medium',9,NULL),
(1,7,'Fold & Polybag','Manual',0.20,0.20,'packing','easy',10,NULL),
-- Base Layer (8)
(1,8,'Tubular Knit','Circular Knit M/C',3.00,3.00,'cutting','medium',1,'Seamless body'),
(1,8,'Sleeve Cut','Straight Knife',0.30,0.30,'cutting','easy',2,NULL),
(1,8,'Shoulder Seam','Flatlock M/C',0.30,0.30,'sewing','easy',3,'Flatlock — no chafe'),
(1,8,'Sleeve Set-in','Flatlock M/C',0.35,0.35,'sewing','easy',4,NULL),
(1,8,'Neck Bind','Coverstitch',0.25,0.25,'sewing','easy',5,NULL),
(1,8,'Hem','Coverstitch',0.20,0.20,'sewing','easy',6,NULL),
(1,8,'Heat Seal Label','Heat Press',0.10,0.10,'finishing','easy',7,NULL),
(1,8,'Quality Check','Manual',0.25,0.25,'quality','medium',8,NULL),
(1,8,'Fold & Polybag','Manual',0.15,0.15,'packing','easy',9,NULL),
-- Denim Jacket (9)
(1,9,'Front Panel Cut','Straight Knife',1.40,1.40,'cutting','hard',1,'Heavy denim'),
(1,9,'Back Panel Cut','Straight Knife',1.00,1.00,'cutting','medium',2,NULL),
(1,9,'Sleeve Cut','Straight Knife',0.60,0.60,'cutting','medium',3,NULL),
(1,9,'Pocket Bag Cut','Straight Knife',0.30,0.30,'cutting','easy',4,NULL),
(1,9,'Collar & Band Cut','Straight Knife',0.40,0.40,'cutting','medium',5,NULL),
(1,9,'Front Chest Pocket','Single Needle',0.90,0.90,'sewing','medium',6,'Welt pocket'),
(1,9,'Front Bottom Pockets','Single Needle',1.20,1.20,'sewing','medium',7,'Flap pockets'),
(1,9,'Back Yoke','Single Needle',0.70,0.70,'sewing','medium',8,NULL),
(1,9,'Collar Attach','Single Needle',1.00,1.00,'sewing','hard',9,'Band collar'),
(1,9,'Front Zipper','Single Needle',0.80,0.80,'sewing','medium',10,NULL),
(1,9,'Sleeve Set-in','Overlock',0.85,0.85,'sewing','medium',11,NULL),
(1,9,'Side Seam','Overlock',0.60,0.60,'sewing','easy',12,NULL),
(1,9,'Cuff Construct','Single Needle',0.70,0.70,'sewing','medium',13,NULL),
(1,9,'Waistband','Lockstitch',0.65,0.65,'sewing','medium',14,NULL),
(1,9,'Rivet Attach','Rivet M/C',0.30,0.30,'sewing','easy',15,'Copper rivets'),
(1,9,'Buttonhole & Button','Buttonhole M/C',0.50,0.50,'sewing','medium',16,NULL),
(1,9,'Distress/Wash','Wash Plant',0.00,0.00,'finishing','hard',17,'Stone wash finish'),
(1,9,'Press','Steam Press',0.80,0.80,'finishing','medium',18,NULL),
(1,9,'Quality Check','Manual',0.60,0.60,'quality','hard',19,'Detailed inspection'),
(1,9,'Hang & Cover','Manual',0.35,0.35,'packing','easy',20,NULL);

-- ============================================================
-- 7. STYLE_COSTING — Costing versions
-- ============================================================
INSERT INTO style_costing (company_id, style_id, version, material_cost, manufacturing_cost, overhead_cost, compliance_cost, packaging_cost, total_cost, margin_pct, fob_price, currency_code, status, notes) VALUES
(1,1,1, 5.40, 1.80, 0.90, 0.30, 0.45, 8.85, 35.00, 12.10,'USD','final','Standard T-shirt costing'),
(1,2,1, 7.65, 2.80, 1.20, 0.40, 0.55, 12.60, 38.00, 17.40,'USD','final','Chino pants v1'),
(1,3,1, 18.50, 6.50, 2.80, 1.20, 1.80, 30.80, 42.00, 42.70,'USD','final','Wool blazer premium'),
(1,4,1, 22.00, 4.50, 1.80, 0.60, 1.50, 30.40, 45.00, 44.08,'USD','final','Cashmere premium'),
(1,5,1, 2.85, 1.20, 0.60, 0.20, 0.30, 5.15, 40.00, 7.21,'USD','final','Running shorts'),
(1,6,1, 8.90, 2.50, 1.10, 0.35, 0.60, 13.45, 38.00, 18.56,'USD','final','Hoodie standard'),
(1,7,1, 5.20, 1.80, 0.80, 0.25, 0.35, 8.40, 42.00, 11.73,'USD','final','Performance tights'),
(1,8,1, 3.60, 1.00, 0.50, 0.15, 0.25, 5.50, 38.00, 7.59,'USD','final','HeatTech base layer'),
(1,9,1, 11.50, 4.20, 2.00, 0.80, 1.20, 19.70, 40.00, 27.36,'USD','final','Denim jacket v1'),
(1,1,2, 5.10, 1.75, 0.85, 0.30, 0.42, 8.42, 36.00, 11.38,'USD','draft','Optimized material sourcing'),
(1,9,2, 10.80, 4.00, 1.90, 0.80, 1.15, 18.65, 42.00, 25.16,'USD','draft','Alternative wash process');

-- ============================================================
-- 8. STYLE_COST_COMPONENTS — Cost breakdown line items
-- ============================================================
INSERT INTO style_cost_components (company_id, style_id, costing_id, category, item_name, cost, notes) VALUES
-- T-Shirt (costing_id=1)
(1,1,1,'material','Cotton Jersey Fabric',3.20,'1.2kg × $4.50/kg'),
(1,1,1,'material','Rib Collar',0.50,'0.15kg × $8.00/kg'),
(1,1,1,'material','Shoulder Tape',0.10,'0.05kg × $2.50/kg'),
(1,1,1,'material','Labels & Tags',0.20,'Main + care labels'),
(1,1,1,'manufacturing','Cutting',0.45,'2.0 SMV'),
(1,1,1,'manufacturing','Sewing',1.05,'4.65 SMV'),
(1,1,1,'manufacturing','Finishing',0.30,'Trim + press'),
(1,1,1,'overhead','Factory Overhead',0.90,'15% of manufacturing'),
(1,1,1,'compliance','Quality Testing',0.30,'AQL inspection'),
(1,1,1,'packaging','Polybag + Carton',0.45,'Per piece packing'),
-- Chino (costing_id=2)
(1,2,2,'material','Cotton Twill Fabric',5.80,'1.35kg × $5.80/kg'),
(1,2,2,'material','Zipper + Button',0.60,'YKK + metal button'),
(1,2,2,'material','Belt Loop + Labels',0.45,'Webbing + labels'),
(1,2,2,'material','Pocketing Fabric',0.80,'Poly-cotton pocketing'),
(1,2,2,'manufacturing','Cutting',0.60,'4.5 SMV'),
(1,2,2,'manufacturing','Sewing',1.80,'10.5 SMV'),
(1,2,2,'manufacturing','Press & Finish',0.40,'Steam press'),
(1,2,2,'overhead','Factory Overhead',1.20,'15% overhead'),
(1,2,2,'compliance','Quality Testing',0.40,'AQL inspection'),
(1,2,2,'packaging','Tissue + Polybag',0.55,'Premium fold'),
-- Blazer (costing_id=3)
(1,3,3,'material','Wool Blend Shell',12.50,'1.8kg × $12.50/kg'),
(1,3,3,'material','Polyester Lining',2.88,'0.9kg × $3.20/kg'),
(1,3,3,'material','Interlining + Pads',2.60,'Fusible + shoulder pads'),
(1,3,3,'material','Buttons + Labels',0.52,'Horn buttons + labels'),
(1,3,3,'manufacturing','Cutting',0.80,'Complex layout'),
(1,3,3,'manufacturing','Sewing',4.50,'20 SMV'),
(1,3,3,'manufacturing','Press & Shape',1.20,'Critical pressing'),
(1,3,3,'overhead','Factory Overhead',2.80,'15% overhead'),
(1,3,3,'compliance','Quality Testing',1.20,'Premium QC'),
(1,3,3,'packaging','Suit Cover + Hanger',1.80,'Non-woven cover'),
-- Sweater (costing_id=4)
(1,4,4,'material','Cashmere Yarn',20.00,'0.45kg × $38/kg'),
(1,4,4,'material','Rib Trim',1.20,'Cuffs + hem'),
(1,4,4,'material','Labels',0.32,'Brand + care labels'),
(1,4,4,'manufacturing','Knitting',2.50,'Flat knit M/C'),
(1,4,4,'manufacturing','Linking',1.50,'Hand linking'),
(1,4,4,'manufacturing','Wash & Block',0.50,'Cashmere wash'),
(1,4,4,'overhead','Factory Overhead',1.80,'15% overhead'),
(1,4,4,'compliance','Quality Testing',0.60,'Quality check'),
(1,4,4,'packaging','Gift Box + Tissue',1.50,'Premium retail box'),
-- Running Shorts (costing_id=5)
(1,5,5,'material','Dri-FIT Fabric',1.71,'0.45kg × $3.80/kg'),
(1,5,5,'material','Mesh Lining',0.63,'0.25kg × $2.50/kg'),
(1,5,5,'material','Elastic + Drawcord',0.20,'Waistband materials'),
(1,5,5,'material','Labels + Transfer',0.35,'Reflective + labels'),
(1,5,5,'manufacturing','Cutting',0.25,'1.8 SMV'),
(1,5,5,'manufacturing','Sewing',0.75,'4.5 SMV'),
(1,5,5,'manufacturing','Heat Press',0.20,'Reflective transfer'),
(1,5,5,'overhead','Factory Overhead',0.60,'15% overhead'),
(1,5,5,'compliance','Quality Testing',0.20,'Standard QC'),
(1,5,5,'packaging','Polybag',0.30,'Individual bag'),
-- Hoodie (costing_id=6)
(1,6,6,'material','Fleece Fabric',8.80,'1.6kg × $5.50/kg'),
(1,6,6,'material','Rib Trim + Drawcord',0.72,'Pocket + drawcord'),
(1,6,6,'material','Eyelets + Labels',0.23,'Metal eyelets + labels'),
(1,6,6,'manufacturing','Cutting',0.55,'4.25 SMV'),
(1,6,6,'manufacturing','Sewing',1.55,'10.15 SMV'),
(1,6,6,'manufacturing','Thread + Eyelet',0.40,'Drawcord assembly'),
(1,6,6,'overhead','Factory Overhead',1.10,'15% overhead'),
(1,6,6,'compliance','Quality Testing',0.35,'Standard QC'),
(1,6,6,'packaging','Polybag + Carton',0.60,'Per piece packing'),
-- Running Tights (costing_id=7)
(1,7,7,'material','Spandex/Poly Fabric',3.41,'0.55kg × $6.20/kg'),
(1,7,7,'material','Elastic Waistband',0.18,'0.8m × $0.22/m'),
(1,7,7,'material','Reflective Print + Label',0.40,'Print + brand label'),
(1,7,7,'manufacturing','Cutting',0.30,'2.4 SMV'),
(1,7,7,'manufacturing','Sewing (Flatlock)',1.15,'7.5 SMV'),
(1,7,7,'manufacturing','Heat Press',0.25,'Reflective'),
(1,7,7,'overhead','Factory Overhead',0.80,'15% overhead'),
(1,7,7,'compliance','Quality Testing',0.25,'Standard QC'),
(1,7,7,'packaging','Polybag',0.35,'Individual bag'),
-- Base Layer (costing_id=8)
(1,8,8,'material','HeatTech Fabric',1.92,'0.4kg × $4.80/kg'),
(1,8,8,'material','Thread + Label',0.13,'Flatlock thread + label'),
(1,8,8,'manufacturing','Knitting',0.50,'Circular knit M/C'),
(1,8,8,'manufacturing','Sewing',0.35,'3.2 SMV'),
(1,8,8,'manufacturing','Heat Seal Label',0.15,'No-tag application'),
(1,8,8,'overhead','Factory Overhead',0.50,'15% overhead'),
(1,8,8,'compliance','Quality Testing',0.15,'Standard QC'),
(1,8,8,'packaging','Polybag',0.25,'Compact bag'),
-- Denim Jacket (costing_id=9)
(1,9,9,'material','Raw Denim',13.50,'1.8kg × $7.50/kg'),
(1,9,9,'material','Lining Fabric',1.68,'0.6kg × $2.80/kg'),
(1,9,9,'material','Zipper + Rivets + Buttons',1.50,'YKK zip + copper rivets'),
(1,9,9,'material','Labels + Leather Patch',0.59,'Brand label + patch'),
(1,9,9,'manufacturing','Cutting',0.70,'5.2 SMV'),
(1,9,9,'manufacturing','Sewing',2.80,'16 SMV'),
(1,9,9,'manufacturing','Wash & Finish',0.70,'Stone wash'),
(1,9,9,'overhead','Factory Overhead',2.00,'15% overhead'),
(1,9,9,'compliance','Quality Testing',0.80,'Detailed QC'),
(1,9,9,'packaging','Butcher Wrap + Carton',1.20,'Premium wrap');

-- ============================================================
-- 9. STYLE_PACKAGING — Packaging materials
-- ============================================================
INSERT INTO style_packaging (company_id, style_id, item_name, quantity, rate, uom, notes) VALUES
(1,1,'Individual Polybag 30×40cm',1.0000,0.03,'Pcs','LDPE polybag'),
(1,1,'Carton Box 60×40×40cm',0.0625,0.85,'Pcs','16 pcs/carton'),
(1,1,'Carton Tape 48mm',0.5000,0.05,'M','Sealing tape'),
(1,1,'Size Sticker',1.0000,0.01,'Pcs','Barcode + size'),
(1,2,'Tissue Paper',1.0000,0.06,'Pcs','Individual fold wrap'),
(1,2,'Polybag 35×50cm',1.0000,0.04,'Pcs','LDPE polybag'),
(1,2,'Carton Box 60×40×40cm',0.0625,0.85,'Pcs','16 pcs/carton'),
(1,2,'Hang Tag',1.0000,0.08,'Pcs','Brand hang tag'),
(1,2,'Price Sticker',1.0000,0.02,'Pcs','UPC barcode'),
(1,3,'Suit Cover Non-Woven',1.0000,0.65,'Pcs','Breathable cover'),
(1,3,'Hanger — Heavy Duty',1.0000,0.35,'Pcs','40mm shoulder'),
(1,3,'Carton Box 70×50×30cm',0.1000,1.20,'Pcs','10 pcs/carton'),
(1,3,'Tissue Paper',2.0000,0.08,'Pcs','Double fold'),
(1,4,'Rigid Gift Box 35×25×8cm',1.0000,1.20,'Pcs','Premium box'),
(1,4,'Tissue Paper',2.0000,0.08,'Pcs','Double layer'),
(1,4,'Satin Ribbon',0.3000,0.15,'M','Box tie'),
(1,4,'Care Card',1.0000,0.05,'Pcs','Cashmere care guide'),
(1,5,'Polybag 25×35cm',1.0000,0.02,'Pcs','LDPE polybag'),
(1,5,'Carton Box 60×40×40cm',0.0833,0.85,'Pcs','12 pcs/carton'),
(1,5,'Size Sticker',1.0000,0.01,'Pcs','Barcode + size'),
(1,6,'Polybag 40×55cm',1.0000,0.05,'Pcs','LDPE polybag'),
(1,6,'Carton Box 60×40×40cm',0.0833,0.85,'Pcs','12 pcs/carton'),
(1,6,'Hang Tag',1.0000,0.08,'Pcs','Brand hang tag'),
(1,6,'Size Sticker',1.0000,0.01,'Pcs','Barcode + size'),
(1,7,'Polybag 25×40cm',1.0000,0.03,'Pcs','LDPE polybag'),
(1,7,'Carton Box 60×40×40cm',0.0625,0.85,'Pcs','16 pcs/carton'),
(1,8,'Polybag 20×30cm',1.0000,0.02,'Pcs','Compact bag'),
(1,8,'Carton Box 50×40×30cm',0.1000,0.70,'Pcs','10 pcs/carton'),
(1,9,'Butcher Paper Wrap',1.0000,0.12,'Pcs','Individual wrap'),
(1,9,'Carton Box 60×40×40cm',0.1000,0.85,'Pcs','10 pcs/carton'),
(1,9,'Hang Tag + Price Tag',1.0000,0.10,'Pcs','Leather-look tag'),
(1,9,'Carton Tape 48mm',0.5000,0.05,'M','Sealing tape');

-- ============================================================
-- 10. STYLE_COMPLIANCE — Testing & compliance
-- ============================================================
INSERT INTO style_compliance (company_id, style_id, category, item_name, cost, required, status, notes) VALUES
(1,1,'testing','Shrinkage Test',25.00,1,'completed','AATCC 135'),
(1,1,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,1,'testing','Pilling Resistance',20.00,1,'in_progress','ISO 12945-2'),
(1,1,'audit','Factory Social Audit',500.00,1,'completed','SEDEX member'),
(1,2,'testing','Shrinkage Test',25.00,1,'completed','AATCC 135'),
(1,2,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,2,'testing','Seam Strength',15.00,1,'completed','ASTM D1683'),
(1,2,'audit','Factory Social Audit',500.00,1,'completed','SEDEX'),
(1,2,'sustainability','OEKO-TEX Standard 100',200.00,1,'in_progress','Class II'),
(1,3,'testing','Color Fastness Dry Cleaning',35.00,1,'completed','ISO 105-D01'),
(1,3,'testing','Pilling Resistance',20.00,1,'completed','ISO 12945-2'),
(1,3,'testing','Shrinkage Test',25.00,1,'completed','AATCC 135'),
(1,3,'audit','Factory Social Audit',500.00,1,'completed','BSCI'),
(1,3,'certification','Woolmark Blend',350.00,1,'in_progress','Woolmark license'),
(1,4,'testing','Cashmere Content Test',45.00,1,'completed','ISO 1833'),
(1,4,'testing','Pilling Resistance',20.00,1,'completed','ISO 12945-2'),
(1,4,'testing','Color Fastness',30.00,1,'in_progress','ISO 105'),
(1,4,'audit','Factory Social Audit',500.00,1,'completed','SEDEX'),
(1,4,'sustainability','Cashmere Traceability',150.00,1,'in_progress','Origin tracking'),
(1,5,'testing','Moisture Wicking Test',25.00,1,'completed','AATCC 195'),
(1,5,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,5,'audit','Factory Social Audit',500.00,1,'completed','SEDEX'),
(1,5,'sustainability','bluesign System',250.00,1,'in_progress','Chemical safety'),
(1,6,'testing','Shrinkage Test',25.00,1,'completed','AATCC 135'),
(1,6,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,6,'testing','Pilling Resistance',20.00,1,'pending','ISO 12945-2'),
(1,6,'audit','Factory Social Audit',500.00,1,'completed','SEDEX'),
(1,7,'testing','Elasticity Recovery',20.00,1,'completed','ASTM D3107'),
(1,7,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,7,'testing','UV Protection Factor',35.00,1,'in_progress','AS/NZS 4399'),
(1,7,'audit','Factory Social Audit',500.00,1,'completed','SEDEX'),
(1,8,'testing','Thermal Resistance',40.00,1,'completed','ISO 11092'),
(1,8,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,8,'audit','Factory Social Audit',500.00,1,'completed','BSCI'),
(1,9,'testing','Shrinkage Test',25.00,1,'completed','AATCC 135'),
(1,9,'testing','Color Fastness Wash',30.00,1,'completed','ISO 105-C06'),
(1,9,'testing','Abrasion Resistance',25.00,1,'completed','ISO 12947'),
(1,9,'testing','Seam Strength',15.00,1,'completed','ASTM D1683'),
(1,9,'audit','Factory Social Audit',500.00,1,'completed','SEDEX'),
(1,9,'sustainability','Organic Cotton Content',120.00,1,'in_progress','GOTS certification');

-- ============================================================
-- 11. STYLE_DOCUMENTS — Attached documents
-- ============================================================
INSERT INTO style_documents (company_id, style_id, doc_type, doc_name, file_path) VALUES
(1,1,'tech_pack','T-Shirt Tech Pack v1.0','/docs/styles/1/tech_pack_v1.pdf'),
(1,1,'spec_sheet','T-Shirt Spec Sheet','/docs/styles/1/spec_sheet.pdf'),
(1,1,'image','Front Flat Sketch','/docs/styles/1/flat_front.png'),
(1,1,'image','Back Flat Sketch','/docs/styles/1/flat_back.png'),
(1,2,'tech_pack','Chino Tech Pack v1.0','/docs/styles/2/tech_pack_v1.pdf'),
(1,2,'spec_sheet','Chino Spec Sheet','/docs/styles/2/spec_sheet.pdf'),
(1,2,'image','Front Flat Sketch','/docs/styles/2/flat_front.png'),
(1,2,'3d_model','3D Rendering','/docs/styles/2/3d_model.obj'),
(1,3,'tech_pack','Blazer Tech Pack v1.0','/docs/styles/3/tech_pack_v1.pdf'),
(1,3,'spec_sheet','Blazer Spec Sheet','/docs/styles/3/spec_sheet.pdf'),
(1,3,'image','Front Flat Sketch','/docs/styles/3/flat_front.png'),
(1,3,'image','Back Flat Sketch','/docs/styles/3/flat_back.png'),
(1,3,'image','Detail Close-up','/docs/styles/3/detail_collar.png'),
(1,4,'tech_pack','Sweater Tech Pack v1.0','/docs/styles/4/tech_pack_v1.pdf'),
(1,4,'spec_sheet','Sweater Spec Sheet','/docs/styles/4/spec_sheet.pdf'),
(1,5,'tech_pack','Shorts Tech Pack v1.0','/docs/styles/5/tech_pack_v1.pdf'),
(1,5,'spec_sheet','Shorts Spec Sheet','/docs/styles/5/spec_sheet.pdf'),
(1,5,'image','Front Flat Sketch','/docs/styles/5/flat_front.png'),
(1,6,'tech_pack','Hoodie Tech Pack v1.0','/docs/styles/6/tech_pack_v1.pdf'),
(1,6,'spec_sheet','Hoodie Spec Sheet','/docs/styles/6/spec_sheet.pdf'),
(1,6,'image','Front Flat Sketch','/docs/styles/6/flat_front.png'),
(1,6,'image','Back Flat Sketch','/docs/styles/6/flat_back.png'),
(1,7,'tech_pack','Tights Tech Pack v1.0','/docs/styles/7/tech_pack_v1.pdf'),
(1,7,'spec_sheet','Tights Spec Sheet','/docs/styles/7/spec_sheet.pdf'),
(1,8,'tech_pack','Base Layer Tech Pack v1.0','/docs/styles/8/tech_pack_v1.pdf'),
(1,8,'spec_sheet','Base Layer Spec Sheet','/docs/styles/8/spec_sheet.pdf'),
(1,9,'tech_pack','Denim Jacket Tech Pack v1.0','/docs/styles/9/tech_pack_v1.pdf'),
(1,9,'spec_sheet','Denim Jacket Spec Sheet','/docs/styles/9/spec_sheet.pdf'),
(1,9,'image','Front Flat Sketch','/docs/styles/9/flat_front.png'),
(1,9,'image','Back Flat Sketch','/docs/styles/9/flat_back.png'),
(1,9,'image','Wash Detail','/docs/styles/9/wash_detail.png');

-- ============================================================
-- 12. STYLE_AI_ANALYSIS — AI-generated insights
-- ============================================================
INSERT INTO style_ai_analysis (company_id, style_id, analysis_type, summary, recommendation, potential_saving, risk_level, confidence) VALUES
(1,1,'cost_optimization','Fabric cost is 36% of total. Bulk sourcing from Vietnam could reduce by 8%.','Negotiate volume discount with FabricMart or consider alternative supplier in Bangladesh.',0.43,'low',85.00),
(1,1,'supplier_alternative','Current trim supplier charges premium. Similar quality available from local sources.','Trial local trim supplier for shoulder tape — potential 20% savings.',0.08,'low',78.00),
(1,2,'cost_optimization','Elastane component adds 15% to fabric cost. Consider 98/2 blend vs current.','Review if 2% elastane is required — could use 100% cotton for relaxed fit.',1.15,'medium',72.00),
(1,3,'risk_assessment','Wool blend supply chain has seasonal volatility. Q4 prices may spike 12-18%.','Lock in wool pricing for next 6 months via forward contract.',NULL,'high',90.00),
(1,3,'cost_optimization','Shoulder pad + interlining cost is 11% of material cost. Alternative construction possible.','Consider fused shoulder construction to eliminate separate pad cost.',0.65,'medium',68.00),
(1,4,'cost_optimization','Cashmere cost is dominant at 73% of material cost. Fiber grade selection opportunity.','Grade down from A to A/B cashmere — 15% savings with minimal visual impact.',3.30,'medium',75.00),
(1,4,'profitability','Current margin at 45% is strong. Market supports premium positioning.','Maintain premium pricing. Consider limited edition marketing.',NULL,'low',88.00),
(1,5,'consumption','Shorts consumption is efficient at 0.45kg. Marker efficiency could improve 3% with nesting.','Use automated marker nesting software for better fabric utilization.',0.12,'low',82.00),
(1,6,'cost_optimization','Fleece fabric accounts for 66% of material cost. Blend ratio adjustment possible.','Consider 80/20 cotton/poly instead of current 60/40 — same handfeel, lower cost.',0.89,'low',76.00),
(1,7,'risk_assessment','Spandex supply from China faces tariff uncertainty. 10-15% cost risk.','Diversify spandex sourcing to India or Taiwan suppliers.',NULL,'medium',80.00),
(1,8,'cost_optimization','HeatTech synthetic fabric is proprietary. Generic equivalent available at 12% less.','Evaluate Korean synthetic alternative — similar thermal performance.',0.43,'medium',70.00),
(1,9,'cost_optimization','Stone wash process adds $0.70/unit. Enzyme wash alternative is cheaper and eco-friendlier.','Switch to enzyme wash — 40% process cost reduction, better sustainability profile.',0.28,'low',85.00),
(1,9,'supplier_alternative','Denim sourcing limited to 2 domestic mills. Consider Turkey or Pakistan origins.','Qualify Turkish denim mill for 10% cost advantage on 12oz raw.',1.15,'medium',74.00);

-- ============================================================
-- 13. STYLE_APPROVALS — Approval workflow
-- ============================================================
INSERT INTO style_approvals (company_id, style_id, approval_level, role_name, status, remarks, acted_at) VALUES
(1,1,1,'Merchandiser','approved','Costing confirmed. Ready for sampling.','2025-01-15 10:30:00'),
(1,1,2,'Design Manager','approved','Design and colorways approved.','2025-01-16 14:00:00'),
(1,1,3,'Production Manager','approved','SMV confirmed. Line allocation ready.','2025-01-17 09:15:00'),
(1,1,4,'Quality Manager','approved','AQL standards confirmed.','2025-01-17 11:00:00'),
(1,1,5,'Commercial Manager','approved','FOB price approved at $12.10.','2025-01-18 10:00:00'),
(1,2,1,'Merchandiser','approved','Costing finalized.','2025-02-01 09:00:00'),
(1,2,2,'Design Manager','approved','Colorways confirmed.','2025-02-02 11:30:00'),
(1,2,3,'Production Manager','approved','Line ready.','2025-02-03 08:45:00'),
(1,2,4,'Quality Manager','pending','Awaiting AQL spec confirmation.',NULL),
(1,2,5,'Commercial Manager','pending','FOB under review.',NULL),
(1,3,1,'Merchandiser','approved','Premium costing approved.','2025-01-20 10:00:00'),
(1,3,2,'Design Manager','approved','Design finalized.','2025-01-21 15:00:00'),
(1,3,3,'Production Manager','approved','Complex construction confirmed.','2025-01-22 09:00:00'),
(1,3,4,'Quality Manager','pending','Awaiting testing results.',NULL),
(1,3,5,'Commercial Manager','pending','FOB under negotiation.',NULL),
(1,4,1,'Merchandiser','approved','Cashmere costing approved.','2025-02-10 10:00:00'),
(1,4,2,'Design Manager','approved','Colorways approved.','2025-02-11 14:30:00'),
(1,4,3,'Production Manager','approved','Knit schedule confirmed.','2025-02-12 09:00:00'),
(1,4,4,'Quality Manager','pending','Pilling test pending.',NULL),
(1,4,5,'Commercial Manager','approved','Premium pricing confirmed at $44.08.','2025-02-13 11:00:00'),
(1,5,1,'Merchandiser','approved','Cost approved.','2025-03-01 09:00:00'),
(1,5,2,'Design Manager','approved','All colorways confirmed.','2025-03-02 10:00:00'),
(1,5,3,'Production Manager','approved','Standard line allocation.','2025-03-02 14:00:00'),
(1,5,4,'Quality Manager','approved','AQL confirmed.','2025-03-03 09:00:00'),
(1,5,5,'Commercial Manager','approved','FOB approved.','2025-03-03 11:00:00'),
(1,6,1,'Merchandiser','approved','Standard hoodie costing.','2025-03-10 09:00:00'),
(1,6,2,'Design Manager','approved','Designs confirmed.','2025-03-11 10:00:00'),
(1,6,3,'Production Manager','pending','Line allocation pending.',NULL),
(1,6,4,'Quality Manager','pending','Awaiting spec.',NULL),
(1,6,5,'Commercial Manager','pending','FOB review.',NULL),
(1,7,1,'Merchandiser','approved','Performance costing approved.','2025-03-15 09:00:00'),
(1,7,2,'Design Manager','approved','Colorways finalized.','2025-03-16 11:00:00'),
(1,7,3,'Production Manager','approved','Specialized line confirmed.','2025-03-17 08:00:00'),
(1,7,4,'Quality Manager','pending','UV test pending.',NULL),
(1,7,5,'Commercial Manager','approved','FOB approved.','2025-03-18 10:00:00'),
(1,8,1,'Merchandiser','approved','HeatTech costing confirmed.','2025-04-01 09:00:00'),
(1,8,2,'Design Manager','approved','Minimal design approved.','2025-04-02 10:00:00'),
(1,8,3,'Production Manager','approved','Circular knit line allocated.','2025-04-03 08:00:00'),
(1,8,4,'Quality Manager','pending','Thermal test pending.',NULL),
(1,8,5,'Commercial Manager','approved','FOB at $7.59.','2025-04-03 14:00:00'),
(1,9,1,'Merchandiser','approved','Denim jacket costing approved.','2025-04-10 09:00:00'),
(1,9,2,'Design Manager','approved','Wash samples approved.','2025-04-11 15:00:00'),
(1,9,3,'Production Manager','approved','Wash plant scheduled.','2025-04-12 08:00:00'),
(1,9,4,'Quality Manager','pending','Abrasion test pending.',NULL),
(1,9,5,'Commercial Manager','pending','FOB under review.',NULL);

-- ============================================================
-- 14. STYLE_VERSIONS — Version history
-- ============================================================
INSERT INTO style_versions (company_id, style_id, version_label, change_description, changed_by) VALUES
(1,1,'V1.0','Initial development — basic cotton t-shirt',1),
(1,1,'V1.1','Adjusted sleeve length +1cm per buyer feedback',1),
(1,1,'V2.0','Updated fabric from 160gsm to 180gsm for better handfeel',1),
(1,2,'V1.0','Initial development — slim fit chino',1),
(1,2,'V1.1','Added 2% elastane for comfort stretch',1),
(1,3,'V1.0','Initial development — wool blend blazer',1),
(1,3,'V1.1','Changed from 2-button to 3-button front',1),
(1,3,'V1.2','Updated shoulder pad from thin to semi-rigid',1),
(1,4,'V1.0','Initial development — cashmere sweater',1),
(1,4,'V1.1','Changed from 7-gauge to 12-gauge knit for finer handfeel',1),
(1,5,'V1.0','Initial development — running shorts',1),
(1,5,'V1.1','Added reflective transfer for low-light running',1),
(1,6,'V1.0','Initial development — lifestyle hoodie',1),
(1,6,'V1.1','Added kangaroo pocket construction',1),
(1,7,'V1.0','Initial development — running tights',1),
(1,8,'V1.0','Initial development — heat tech base layer',1),
(1,9,'V1.0','Initial development — denim jacket',1),
(1,9,'V1.1','Changed zipper from plastic to YKK brass #8',1),
(1,9,'V1.2','Updated wash from acid wash to stone wash',1);

-- ============================================================
-- 15. STYLE_SIZES — Size definitions with body measurements
-- ============================================================
INSERT INTO style_sizes (company_id, style_id, size_label, size_code, chest, waist, hip, length, sleeve, shoulder, sku_suffix, sequence, status) VALUES
-- T-Shirt (1)
(1,1,'S','S',96.00,76.00,96.00,68.00,20.00,40.00,'-S',1,'active'),
(1,1,'M','M',104.00,84.00,104.00,70.00,21.00,42.00,'-M',2,'active'),
(1,1,'L','L',112.00,92.00,112.00,72.00,22.00,44.00,'-L',3,'active'),
(1,1,'XL','XL',120.00,100.00,120.00,74.00,23.00,46.00,'-XL',4,'active'),
(1,1,'XXL','XXL',128.00,108.00,128.00,76.00,24.00,48.00,'-XXL',5,'active'),
-- Chino (2)
(1,2,'30','30',NULL,76.00,96.00,104.00,NULL,NULL,'-30',1,'active'),
(1,2,'32','32',NULL,81.00,101.00,106.00,NULL,NULL,'-32',2,'active'),
(1,2,'34','34',NULL,86.00,106.00,108.00,NULL,NULL,'-34',3,'active'),
(1,2,'36','36',NULL,91.00,111.00,110.00,NULL,NULL,'-36',4,'active'),
-- Blazer (3)
(1,3,'S','S',96.00,88.00,NULL,68.00,63.00,42.00,'-S',1,'active'),
(1,3,'M','M',102.00,94.00,NULL,70.00,64.50,44.00,'-M',2,'active'),
(1,3,'L','L',108.00,100.00,NULL,72.00,66.00,46.00,'-L',3,'active'),
(1,3,'XL','XL',114.00,106.00,NULL,74.00,67.50,48.00,'-XL',4,'active'),
-- Sweater (4)
(1,4,'S','S',96.00,76.00,NULL,66.00,58.00,40.00,'-S',1,'active'),
(1,4,'M','M',102.00,82.00,NULL,68.00,60.00,42.00,'-M',2,'active'),
(1,4,'L','L',108.00,88.00,NULL,70.00,62.00,44.00,'-L',3,'active'),
(1,4,'XL','XL',114.00,94.00,NULL,72.00,64.00,46.00,'-XL',4,'active'),
-- Running Shorts (5)
(1,5,'S','S',NULL,72.00,92.00,42.00,NULL,NULL,'-S',1,'active'),
(1,5,'M','M',NULL,78.00,98.00,44.00,NULL,NULL,'-M',2,'active'),
(1,5,'L','L',NULL,84.00,104.00,46.00,NULL,NULL,'-L',3,'active'),
(1,5,'XL','XL',NULL,90.00,110.00,48.00,NULL,NULL,'-XL',4,'active'),
-- Hoodie (6)
(1,6,'S','S',96.00,76.00,NULL,66.00,60.00,40.00,'-S',1,'active'),
(1,6,'M','M',104.00,84.00,NULL,68.00,62.00,42.00,'-M',2,'active'),
(1,6,'L','L',112.00,92.00,NULL,70.00,64.00,44.00,'-L',3,'active'),
(1,6,'XL','XL',120.00,100.00,NULL,72.00,66.00,46.00,'-XL',4,'active'),
(1,6,'XXL','XXL',128.00,108.00,NULL,74.00,68.00,48.00,'-XXL',5,'active'),
-- Running Tights (7)
(1,7,'S','S',NULL,72.00,92.00,72.00,NULL,NULL,'-S',1,'active'),
(1,7,'M','M',NULL,78.00,98.00,74.00,NULL,NULL,'-M',2,'active'),
(1,7,'L','L',NULL,84.00,104.00,76.00,NULL,NULL,'-L',3,'active'),
(1,7,'XL','XL',NULL,90.00,110.00,78.00,NULL,NULL,'-XL',4,'active'),
-- Base Layer (8)
(1,8,'S','S',96.00,76.00,NULL,64.00,58.00,40.00,'-S',1,'active'),
(1,8,'M','M',102.00,82.00,NULL,66.00,60.00,42.00,'-M',2,'active'),
(1,8,'L','L',108.00,88.00,NULL,68.00,62.00,44.00,'-L',3,'active'),
(1,8,'XL','XL',114.00,94.00,NULL,70.00,64.00,46.00,'-XL',4,'active'),
-- Denim Jacket (9)
(1,9,'S','S',96.00,88.00,NULL,64.00,60.00,42.00,'-S',1,'active'),
(1,9,'M','M',102.00,94.00,NULL,66.00,62.00,44.00,'-M',2,'active'),
(1,9,'L','L',108.00,100.00,NULL,68.00,64.00,46.00,'-L',3,'active'),
(1,9,'XL','XL',114.00,106.00,NULL,70.00,66.00,48.00,'-XL',4,'active');

-- ============================================================
-- 16. STYLE_TECH_PACK — Tech pack construction details
-- ============================================================
INSERT INTO style_tech_pack (company_id, style_id, construction_details, stitch_type, stitch_density, sewing_instructions, print_placement, embroidery_details, wash_instructions, care_instructions, trim_details, packing_instructions) VALUES
(1,1,
'Classic crew neck t-shirt. Set-in sleeve. 1x1 rib collar. Coverstitch hem and sleeve hem.',
'Safety stitch 5-thread overlock + Coverstitch', '12-14 SPI',
'Stitch shoulder seam first. Attach rib collar using 4-needle coverstitch. Set sleeves. Close side seams. Hem bottom and sleeve openings.',
'Front left chest — 10cm from HPS, centered. Back — full sublimation available.',
NULL,
'No special wash required. Standard tumble dry low.',
'100% cotton — machine wash cold with like colors. Do not bleach. Tumble dry low. Iron on medium heat.',
'Rib collar: 1x1 rib, 220gsm, color-match to body. Shoulder tape: cotton twill 15mm.',
'Individual polybag. Size sticker on bag. 16 pcs per carton. Carton label with PO number.'),
(1,2,
'Slim fit chino pants. Front fly zipper. 2 front slant pockets, 2 back welt pockets. Belt loops. Single pleat option.',
'Safety stitch 5-thread + Lockstitch', '11-13 SPI',
'Sew front darts/pleats. Construct back welt pockets. Attach pocket bags. Install YKK fly zipper. Join inseam and outseam. Attach waistband. Sew belt loops. Hem.',
NULL, NULL,
'Cold wash, hang dry recommended.',
'98% cotton, 2% elastane — machine wash cold. Do not bleach. Hang to dry. Iron on medium.',
'YKK #5 zipper 18cm. Metal shank button 17mm. Belt loop webbing 40mm.',
'Fold with tissue paper. Hang tag attached. Individual polybag.'),
(1,3,
'Two-button notch collar blazer. Full polyester lining. Single back vent. 2 front flap pockets, 1 inner pocket. Shoulder pads.',
'Lockstitch + Overlock', '10-12 SPI',
'Fuse front panels and collar. Sew darts and princess seams. Construct back vent. Make notch collar. Attach lining. Set sleeves. Make buttonholes. Attach buttons. Add shoulder pads.',
NULL, NULL,
'Professional dry clean only.',
'Dry clean only. Store on hanger. Do not press directly on fabric.',
'Horn buttons 20mm × 5. Semi-rigid shoulder pads. Fusible interlining on front + collar.',
'Suit cover on hanger. Tissue paper fold. Individual cover per piece.'),
(1,4,
'12-gauge fully fashioned cashmere crew neck sweater. Rib trim at collar, cuffs, and hem. Linked construction.',
'Linking stitch', '12 GG knit',
'Knit front, back, and sleeves on flat knit machine. Link shoulder seams. Link sleeves to body. Attach rib collar, cuffs, and hem rib.',
NULL, NULL,
'Hand wash cold. Do not wring. Lay flat to dry.',
'100% cashmere — hand wash in cold water with cashmere shampoo. Do not bleach. Lay flat to dry. Store folded with cedar.',
'Cashmere yarn 12gg. Rib trim 2×2.',
'Tissue paper double fold. Ribbon tie. Rigid gift box with care card.'),
(1,5,
'Split-leg running shorts. Elastic waistband with drawcord. Inner mesh brief lining. Reflective heat transfer logo.',
'Overlock + Coverstitch', '12-14 SPI',
'Cut and attach mesh lining to main body. Sew side seams and inseam. Create waistband channel. Thread drawcord. Apply reflective transfer. Hem.',
'Left leg — reflective logo, 5cm above hem.',
NULL,
'Cold wash, tumble dry low.',
'100% polyester Dri-FIT — machine wash cold. Do not iron directly on reflective transfer.',
'Elastic waistband 35mm. Drawcord 5mm flat. Reflective heat transfer.',
'Individual polybag. Size sticker.'),
(1,6,
'Pullover hoodie with kangaroo pocket. Brushed fleece interior. 2-piece hood with drawcord. Rib cuffs and waistband.',
'Safety stitch 5-thread + Coverstitch', '10-12 SPI',
'Sew kangaroo pocket. Construct 2-piece hood. Join shoulder seams. Attach hood. Set sleeves. Close side seams through pocket. Attach rib waistband and cuffs. Thread drawcord through hood. Set eyelets.',
NULL, NULL,
'Cold wash, tumble dry medium.',
'60% cotton, 40% polyester — machine wash cold with like colors. Do not bleach. Tumble dry medium. Iron on low.',
'6mm flat drawcord. Metal eyelets 5mm × 2. Rib trim 2×2 for cuffs and waistband.',
'Individual polybag. Hang tag attached.'),
(1,7,
'4-way stretch running tights. High-rise waistband. Flatlock seams for comfort. Reflective details for visibility.',
'Flatlock + Coverstitch', '12-14 SPI',
'Sew gusset. Join inseam with flatlock. Join outseam with flatlock. Attach wide waistband. Apply reflective print. Heat seal label.',
'Left calf — reflective stripe. Right hip — reflective logo.',
NULL,
'Cold wash. Do not use fabric softener.',
'88% polyester, 12% spandex — machine wash cold. Do not bleach. Do not use fabric softener. Hang to dry.',
'Elastic waistband 30mm wide comfort. Flatlock thread.',
'Individual polybag.'),
(1,8,
'Long-sleeve base layer. Tubular body construction (no side seams). Flatlock shoulder and sleeve seams. Heat seal label.',
'Flatlock + Coverstitch', '14-16 SPI',
'Knit tubular body on circular machine. Cut and attach sleeves with flatlock. Bind neck. Hem bottom. Apply heat seal label.',
NULL, NULL,
'Cold wash. Do not iron on label.',
'Synthetic HeatTech blend — machine wash cold. Do not bleach. Do not iron on heat seal label.',
'Flatlock seam thread for seamless comfort. Heat seal label (no physical tag).',
'Compact fold. Individual polybag.'),
(1,9,
'Classic denim jacket. Button front with YKK brass zipper. 2 chest welt pockets, 2 front flap pockets. Back yoke. Band collar. Copper rivets at stress points.',
'Lockstitch + Overlock + Bartack', '8-10 SPI',
'Sew front chest welt pockets. Construct front flap pockets. Join back yoke. Attach band collar. Install YKK #8 zipper. Set sleeves. Close side seams. Construct cuffs. Attach waistband. Set copper rivets. Make buttonholes.',
'Back yoke — embroidered logo available. Left chest pocket — leather patch.',
'Leather patch 50×70mm on back neck.',
'Stone wash. Enzyme wash alternative available.',
'100% cotton denim — machine wash cold inside out. Do not bleach. Hang to dry. Iron on high.',
'YKK #8 brass zipper. Copper rivets × 12. Shank button 17mm × 4. Leather patch.',
'Butcher paper individual wrap. Hang tag + price tag. 10 pcs per carton.');

-- ============================================================
-- 17. STYLE_PURCHASE — Purchase/procurement tracking
-- ============================================================
INSERT INTO style_purchase (company_id, style_id, item_name, item_type, supplier, required_qty, required_uom, warehouse_qty, reserved_qty, purchase_qty, lead_time_days, unit_cost, currency_code, po_status, notes) VALUES
(1,1,'Cotton Jersey 180gsm','fabric','FabricMart',5000.00,'Kg',2000.00,1500.00,5000.00,14,4.50,'USD','partial_received','PO #FM-2025-001'),
(1,1,'Rib Collar 220gsm','trim','TrimCo',600.00,'Kg',300.00,200.00,600.00,10,8.00,'USD','ordered','PO #TC-2025-012'),
(1,1,'Shoulder Tape 15mm','trim','TrimCo',200.00,'Kg',150.00,50.00,200.00,10,2.50,'USD','received','PO #TC-2025-013'),
(1,1,'Woven Labels','accessory','LabelPro',25000.00,'Pcs',12000.00,8000.00,25000.00,7,0.12,'USD','received','PO #LP-2025-045'),
(1,2,'Cotton Twill 230gsm','fabric','TextilePro',4500.00,'Kg',1200.00,800.00,4500.00,21,5.80,'USD','partial_received','PO #TP-2025-008'),
(1,2,'YKK Zipper #5 18cm','trim','YKK',20000.00,'Pcs',10000.00,5000.00,20000.00,14,0.45,'USD','ordered','PO #YKK-2025-033'),
(1,2,'Metal Button 17mm','accessory','ButtonCraft',20000.00,'Pcs',8000.00,4000.00,20000.00,10,0.15,'USD','partial_received','PO #BC-2025-022'),
(1,3,'Wool Blend 280gsm','fabric','LuxTextiles',3000.00,'Kg',500.00,300.00,3000.00,30,12.50,'USD','ordered','PO #LT-2025-005'),
(1,3,'Polyester Lining 110gsm','fabric','LuxTextiles',1500.00,'Kg',200.00,100.00,1500.00,28,3.20,'USD','ordered','PO #LT-2025-006'),
(1,3,'Horn Buttons 20mm','accessory','ButtonCraft',5000.00,'Pcs',1000.00,500.00,5000.00,14,0.35,'USD','partial_received','PO #BC-2025-028'),
(1,4,'Cashmere Yarn 12gg','fabric','CashMill',200.00,'Kg',0.00,0.00,200.00,45,38.00,'USD','ordered','PO #CM-2025-002 — 45-day lead time'),
(1,5,'Dri-FIT Polyester 130gsm','fabric','NikeFab',2500.00,'Kg',1500.00,1000.00,2500.00,10,3.80,'USD','received','PO #NF-2025-015'),
(1,5,'Mesh Lining 80gsm','fabric','NikeFab',1500.00,'Kg',800.00,400.00,1500.00,10,2.50,'USD','received','PO #NF-2025-016'),
(1,6,'Fleece Cotton/Poly 320gsm','fabric','FleeceMill',6000.00,'Kg',1000.00,500.00,6000.00,18,5.50,'USD','partial_received','PO #FM-2025-020'),
(1,6,'Metal Eyelets 5mm','accessory','AccessoryHub',15000.00,'Pcs',8000.00,3000.00,15000.00,7,0.04,'USD','received','PO #AH-2025-044'),
(1,7,'Spandex/Polyester 200gsm','fabric','PerformanceKnit',3000.00,'Kg',1800.00,1200.00,3000.00,14,6.20,'USD','partial_received','PO #PN-2025-010'),
(1,8,'HeatTech Synthetic 140gsm','fabric','UltraWarm',2000.00,'Kg',0.00,0.00,2000.00,21,4.80,'USD','ordered','PO #UW-2025-003'),
(1,9,'Raw Denim 12oz','fabric','DenimWorks',4000.00,'Kg',800.00,400.00,4000.00,21,7.50,'USD','partial_received','PO #DW-2025-007'),
(1,9,'YKK Brass Zipper #8','trim','YKK',8000.00,'Pcs',3000.00,2000.00,8000.00,14,1.20,'USD','ordered','PO #YKK-2025-038'),
(1,9,'Copper Rivets','accessory','AccessoryHub',100000.00,'Pcs',50000.00,20000.00,100000.00,10,0.06,'USD','received','PO #AH-2025-050'),
(1,9,'Leather Patch 50×70mm','accessory','AccessoryHub',8000.00,'Pcs',0.00,0.00,8000.00,14,0.45,'USD','ordered','PO #AH-2025-051');

-- ============================================================
-- 18. STYLE_PRODUCTION — Production planning
-- ============================================================
INSERT INTO style_production (company_id, style_id, total_smv, total_sam, operators, machines, line_efficiency, daily_capacity, estimated_days, planned_qty, actual_output, start_date, end_date, status, notes) VALUES
(1,1, 6.30,6.30, 20,15, 68.00, 1800, 14, 25000, 12500,'2025-02-01','2025-02-14','in_progress','Line A — running 50% complete'),
(1,2, 10.50,10.50, 25,20, 65.00, 1200, 21, 15000, 6000,'2025-02-15','2025-03-07','in_progress','Line B — 40% complete'),
(1,3, 16.00,16.00, 15,12, 62.00, 400, 30, 8000, 2400,'2025-03-01','2025-03-30','in_progress','Line C — premium line, slow pace'),
(1,4, 20.00,20.00, 10,8, 60.00, 200, 25, 3000, 600,'2025-03-15','2025-04-08','in_progress','Knit line — slow but steady'),
(1,5, 4.50,4.50, 18,12, 70.00, 2200, 10, 20000, 18000,'2025-03-10','2025-03-19','in_progress','Line A overflow — 90% complete'),
(1,6, 10.15,10.15, 22,18, 66.00, 1100, 18, 12000, 0,'2025-04-01','2025-04-18','planned','Pending line allocation'),
(1,7, 7.50,7.50, 12,10, 64.00, 800, 12, 5000, 0,'2025-04-10','2025-04-21','planned','Specialized stretch line'),
(1,8, 3.20,3.20, 15,8, 72.00, 2500, 8, 15000, 0,'2025-04-15','2025-04-22','planned','Circular knit — fast output'),
(1,9, 16.00,16.00, 20,15, 63.00, 600, 25, 10000, 2000,'2025-04-01','2025-04-25','in_progress','Including wash process time');

-- ============================================================
-- 19. STYLE_QA — Quality assurance inspections
-- ============================================================
INSERT INTO style_qa (company_id, style_id, stage, aql_level, sample_size, accepted_qty, rejected_qty, major_defects, minor_defects, critical_defects, result, inspector, inspection_date, remarks) VALUES
(1,1,'fabric_inspection',2.5,20,19,1,1,0,0,'pass','Ahmed Khan','2025-01-28','Fabric quality good — 1 roll with shade variation'),
(1,1,'inline',2.5,80,78,2,2,1,0,'pass','Ahmed Khan','2025-02-10','2 garments with open seam — repaired'),
(1,1,'endline',2.5,50,49,1,1,0,0,'pass','Ahmed Khan','2025-02-14','1 garment with stain — rejected'),
(1,2,'fabric_inspection',2.5,20,18,2,1,2,0,'pass','Sarah Lee','2025-02-10','2 rolls with needle damage'),
(1,2,'inline',2.5,80,76,4,3,2,0,'fail','Sarah Lee','2025-02-25','Back welt pocket stitching inconsistent — rework required'),
(1,2,'inline',2.5,80,79,1,1,0,0,'pass','Sarah Lee','2025-02-27','After rework — acceptable'),
(1,3,'fabric_inspection',1.5,32,31,1,1,0,0,'pass','James Wilson','2025-02-20','Wool fabric inspection — 1 moth damage spot'),
(1,3,'inline',1.5,80,77,3,2,2,0,'fail','James Wilson','2025-03-10','Collar notch alignment issue — rework'),
(1,3,'inline',1.5,80,79,1,1,0,0,'pass','James Wilson','2025-03-12','After collar rework — acceptable'),
(1,4,'fabric_inspection',1.0,20,19,1,1,0,0,'pass','James Wilson','2025-03-08','Cashmere quality inspection — 1 knot defect'),
(1,4,'endline',1.0,30,28,2,1,1,0,'pass','James Wilson','2025-04-01','2 garments with slight pilling — within tolerance'),
(1,5,'inline',2.5,80,79,1,1,0,0,'pass','Maria Garcia','2025-03-15','Running shorts — clean production'),
(1,5,'endline',2.5,50,50,0,0,0,0,'pass','Maria Garcia','2025-03-19','Zero defect — excellent'),
(1,6,'fabric_inspection',2.5,20,20,0,0,0,0,'pass','Maria Garcia','2025-03-25','Fleece quality good'),
(1,7,'inline',2.5,50,48,2,2,0,0,'pass','David Brown','2025-04-15','2 flatlock seam issues — repaired'),
(1,8,'inline',2.5,50,49,1,1,0,0,'pass','David Brown','2025-04-18','1 tubular knit defect — acceptable after QC review'),
(1,9,'fabric_inspection',2.0,32,30,2,2,0,0,'pass','Sarah Lee','2025-04-05','Denim — 2 rolls with irregular weave'),
(1,9,'inline',2.0,80,75,5,3,3,0,'fail','Sarah Lee','2025-04-12','Rivet alignment and zipper issues — rework'),
(1,9,'inline',2.0,80,79,1,1,0,0,'pass','Sarah Lee','2025-04-15','After rework — acceptable');

-- ============================================================
-- 20. STYLE_SUSTAINABILITY — Sustainability certifications
-- ============================================================
INSERT INTO style_sustainability (company_id, style_id, certification_name, cert_type, status, certificate_no, issued_by, issued_date, expiry_date, notes) VALUES
(1,1,'OEKO-TEX Standard 100','chemical','certified','SH025 123456','OEKO-TEX Association','2024-06-15','2025-06-14','Class II — safe for direct skin contact'),
(1,1,'GOTS Organic','organic','applied',NULL,NULL,NULL,NULL,'Application pending — cotton sourcing verification'),
(1,2,'OEKO-TEX Standard 100','chemical','certified','SH025 234567','OEKO-TEX Association','2024-08-01','2025-07-31','Class II — safe for direct skin contact'),
(1,2,'bluesign System','chemical','required',NULL,NULL,NULL,NULL,'Required for elastane component verification'),
(1,3,'Woolmark Blend','social','applied',NULL,'The Woolmark Company',NULL,NULL,'License application submitted — audit pending'),
(1,3,'OEKO-TEX Standard 100','chemical','certified','SH025 345678','OEKO-TEX Association','2024-09-15','2025-09-14','Class II'),
(1,4,'Sustainable Cashmere','social','applied',NULL,'Sustainable Fibre Alliance',NULL,NULL,'Origin tracing from Inner Mongolia'),
(1,4,'OEKO-TEX Standard 100','chemical','required',NULL,NULL,NULL,NULL,'Required — cashmere dyestuff verification'),
(1,5,'bluesign System','chemical','certified','BL025 567890','bluesign technologies','2024-07-01','2025-06-30','Full chemical safety system'),
(1,5,'GRS Recycled','recycled','required',NULL,NULL,NULL,NULL,'Evaluate recycled polyester option for V2'),
(1,6,'OEKO-TEX Standard 100','chemical','applied',NULL,NULL,NULL,NULL,'Pending — cotton/poly blend verification'),
(1,7,'OEKO-TEX Standard 100','chemical','certified','SH025 678901','OEKO-TEX Association','2024-10-01','2025-09-30','Class II — performance fabric'),
(1,7,'GRS Recycled','recycled','applied',NULL,NULL,NULL,NULL,'Recycled polyester certification pending'),
(1,8,'OEKO-TEX Standard 100','chemical','certified','SH025 789012','OEKO-TEX Association','2024-11-01','2025-10-31','Synthetic base layer — chemical safety'),
(1,9,'OEKO-TEX Standard 100','chemical','applied',NULL,NULL,NULL,NULL,'Pending — indigo dye verification'),
(1,9,'GOTS Organic','organic','applied',NULL,NULL,NULL,NULL,'Organic cotton denim — GOTS application submitted'),
(1,9,'Clean Denim Program','environmental','certified','CDP-2025-041','Clean Fashion Initiative','2025-01-15','2026-01-14','Reduced water wash process');


-- ============================================================
-- FILE: migration_packing.sql
-- ============================================================

-- ============================================================
-- FASHCOGNITIVE PACKING MANAGEMENT SYSTEM
-- Migration: migration_packing.sql
-- ============================================================

-- 1. PACKING INSTRUCTIONS (per buyer/style)
CREATE TABLE IF NOT EXISTS `packing_instructions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `buyer_id` int unsigned DEFAULT NULL,
  `style_id` int unsigned DEFAULT NULL,
  `instruction_name` varchar(255) NOT NULL,
  `fold_type` varchar(100) DEFAULT NULL,
  `garment_orientation` varchar(100) DEFAULT NULL,
  `polybag_type` varchar(100) DEFAULT NULL,
  `polybag_size` varchar(50) DEFAULT NULL,
  `sticker_position` varchar(100) DEFAULT NULL,
  `barcode_position` varchar(100) DEFAULT NULL,
  `size_sticker_required` tinyint(1) NOT NULL DEFAULT 0,
  `hanger_required` tinyint(1) NOT NULL DEFAULT 0,
  `hanger_type` varchar(100) DEFAULT NULL,
  `carton_type` varchar(100) DEFAULT NULL DEFAULT '5 Ply Export',
  `carton_weight_max_kg` decimal(6,2) DEFAULT 18.00,
  `carton_length_cm` decimal(6,1) DEFAULT NULL,
  `carton_width_cm` decimal(6,1) DEFAULT NULL,
  `carton_height_cm` decimal(6,1) DEFAULT NULL,
  `pieces_per_carton` int unsigned DEFAULT NULL,
  `carton_printing` text DEFAULT NULL,
  `shipping_marks` text DEFAULT NULL,
  `special_instructions` text DEFAULT NULL,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_company` (`company_id`),
  KEY `idx_buyer` (`buyer_id`),
  KEY `idx_style` (`style_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 2. PACKING ORDERS (generated from Buyer PO)
CREATE TABLE IF NOT EXISTS `packing_orders` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `packing_order_code` varchar(50) NOT NULL,
  `buyer_po_id` int unsigned NOT NULL,
  `buyer_id` int unsigned DEFAULT NULL,
  `style_id` int unsigned DEFAULT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `packing_instruction_id` int unsigned DEFAULT NULL,
  `total_qty` int unsigned NOT NULL DEFAULT 0,
  `total_cartons_planned` int unsigned NOT NULL DEFAULT 0,
  `total_cartons_packed` int unsigned NOT NULL DEFAULT 0,
  `total_pieces_packed` int unsigned NOT NULL DEFAULT 0,
  `pieces_per_carton` int unsigned DEFAULT 50,
  `destination` varchar(255) DEFAULT NULL,
  `shipment_date` date DEFAULT NULL,
  `etd` date DEFAULT NULL,
  `eta` date DEFAULT NULL,
  `shipment_mode` varchar(50) DEFAULT NULL,
  `status` enum('pending','in_progress','packing_complete','palletizing','container_loading','verified','shipped') NOT NULL DEFAULT 'pending',
  `packing_started_at` timestamp NULL DEFAULT NULL,
  `packing_completed_at` timestamp NULL DEFAULT NULL,
  `packing_accuracy` decimal(5,2) DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `created_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_packing_code` (`packing_order_code`),
  KEY `idx_company` (`company_id`),
  KEY `idx_buyer_po` (`buyer_po_id`),
  KEY `idx_buyer` (`buyer_id`),
  KEY `idx_style` (`style_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 3. PACKING ORDER LINES (color/size breakdown)
CREATE TABLE IF NOT EXISTS `packing_order_lines` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `packing_order_id` int unsigned NOT NULL,
  `color` varchar(100) NOT NULL,
  `size` varchar(100) NOT NULL,
  `size_master_id` int unsigned DEFAULT NULL,
  `quantity` int unsigned NOT NULL DEFAULT 0,
  `quantity_packed` int unsigned NOT NULL DEFAULT 0,
  `quantity_remaining` int unsigned NOT NULL DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `size_master_id` (`size_master_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 4. PACKING STATIONS (physical stations in factory)
CREATE TABLE IF NOT EXISTS `packing_stations` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `station_code` varchar(50) NOT NULL,
  `station_name` varchar(255) NOT NULL,
  `factory_id` int unsigned DEFAULT NULL,
  `location` varchar(255) DEFAULT NULL,
  `has_scale` tinyint(1) NOT NULL DEFAULT 0,
  `has_camera` tinyint(1) NOT NULL DEFAULT 0,
  `has_printer` tinyint(1) NOT NULL DEFAULT 1,
  `has_scanner` tinyint(1) NOT NULL DEFAULT 1,
  `status` enum('active','inactive','maintenance') NOT NULL DEFAULT 'active',
  `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_station_code` (`station_code`),
  KEY `idx_company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 5. PACKING SESSIONS (active packing runs)
CREATE TABLE IF NOT EXISTS `packing_sessions` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `session_code` varchar(50) NOT NULL,
  `packing_order_id` int unsigned NOT NULL,
  `station_id` int unsigned DEFAULT NULL,
  `operator_name` varchar(255) DEFAULT NULL,
  `operator_id` int unsigned DEFAULT NULL,
  `carton_number` int unsigned NOT NULL DEFAULT 1,
  `carton_code` varchar(50) DEFAULT NULL,
  `pieces_packed` int unsigned NOT NULL DEFAULT 0,
  `target_pieces` int unsigned NOT NULL DEFAULT 0,
  `session_status` enum('active','paused','completed','cancelled') NOT NULL DEFAULT 'active',
  `started_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `completed_at` timestamp NULL DEFAULT NULL,
  `notes` text 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_session_code` (`session_code`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_station` (`station_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 6. CARTONS (individual cartons)
CREATE TABLE IF NOT EXISTS `cartons` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `carton_code` varchar(50) NOT NULL,
  `packing_order_id` int unsigned NOT NULL,
  `session_id` int unsigned DEFAULT NULL,
  `pallet_id` int unsigned DEFAULT NULL,
  `container_id` int unsigned DEFAULT NULL,
  `carton_seq` int unsigned NOT NULL DEFAULT 1,
  `total_qty` int unsigned NOT NULL DEFAULT 0,
  `weight_kg` decimal(8,2) DEFAULT NULL,
  `length_cm` decimal(6,1) DEFAULT NULL,
  `width_cm` decimal(6,1) DEFAULT NULL,
  `height_cm` decimal(6,1) DEFAULT NULL,
  `cbm` decimal(8,4) DEFAULT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size_range` varchar(100) DEFAULT NULL,
  `is_mixed` tinyint(1) NOT NULL DEFAULT 0,
  `is_sealed` tinyint(1) NOT NULL DEFAULT 0,
  `seal_number` varchar(100) DEFAULT NULL,
  `label_printed` tinyint(1) NOT NULL DEFAULT 0,
  `qr_code` varchar(500) DEFAULT NULL,
  `barcode` varchar(255) DEFAULT NULL,
  `status` enum('packing','packed','labeled','palletized','loaded','shipped') NOT NULL DEFAULT 'packing',
  `packed_at` timestamp NULL DEFAULT NULL,
  `sealed_at` timestamp NULL 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_carton_code` (`carton_code`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_pallet` (`pallet_id`),
  KEY `idx_container` (`container_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 7. CARTON ITEMS (garments inside each carton — fully traceable)
CREATE TABLE IF NOT EXISTS `carton_items` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `carton_id` int unsigned NOT NULL,
  `packing_order_line_id` int unsigned DEFAULT NULL,
  `color` varchar(100) NOT NULL,
  `size` varchar(100) NOT NULL,
  `quantity` int unsigned NOT NULL DEFAULT 0,
  `barcode` varchar(255) DEFAULT NULL,
  `garment_barcode` varchar(255) DEFAULT NULL,
  `verified` tinyint(1) NOT NULL DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_line` (`packing_order_line_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 8. CARTON IMAGES (photos per carton)
CREATE TABLE IF NOT EXISTS `carton_images` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `carton_id` int unsigned NOT NULL,
  `image_type` enum('packing','label','seal','pallet','container','other') NOT NULL DEFAULT 'packing',
  `file_path` varchar(500) DEFAULT NULL,
  `caption` varchar(255) DEFAULT NULL,
  `uploaded_by` int unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_carton` (`carton_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 9. PALLETS
CREATE TABLE IF NOT EXISTS `pallets` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `pallet_code` varchar(50) NOT NULL,
  `packing_order_id` int unsigned NOT NULL,
  `total_cartons` int unsigned NOT NULL DEFAULT 0,
  `total_qty` int unsigned NOT NULL DEFAULT 0,
  `weight_kg` decimal(8,2) DEFAULT NULL,
  `height_cm` decimal(6,1) DEFAULT NULL,
  `length_cm` decimal(6,1) DEFAULT NULL,
  `width_cm` decimal(6,1) DEFAULT NULL,
  `cbm` decimal(8,4) DEFAULT NULL,
  `is_stacked` tinyint(1) NOT NULL DEFAULT 0,
  `is_wrapped` tinyint(1) NOT NULL DEFAULT 0,
  `ai_load_balance` varchar(50) DEFAULT 'balanced',
  `status` enum('building','complete','loaded') NOT NULL DEFAULT 'building',
  `completed_at` timestamp NULL 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_pallet_code` (`pallet_code`),
  KEY `idx_packing_order` (`packing_order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 10. PALLET CARTONS (link table)
CREATE TABLE IF NOT EXISTS `pallet_cartons` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `pallet_id` int unsigned NOT NULL,
  `carton_id` int unsigned NOT NULL,
  `position_x` int unsigned DEFAULT 0,
  `position_y` int unsigned DEFAULT 0,
  `position_z` int unsigned DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_pallet_carton` (`pallet_id`, `carton_id`),
  KEY `idx_carton` (`carton_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 11. CONTAINERS
CREATE TABLE IF NOT EXISTS `packing_containers` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `container_code` varchar(50) NOT NULL,
  `container_number` varchar(50) DEFAULT NULL,
  `container_type` enum('20ft','40ft','40ft_hq','20ft_open','40ft_open') NOT NULL DEFAULT '40ft',
  `packing_order_id` int unsigned DEFAULT NULL,
  `seal_number` varchar(100) DEFAULT NULL,
  `max_weight_kg` decimal(10,2) DEFAULT 26000.00,
  `max_cbm` decimal(8,4) DEFAULT 67.7000,
  `current_weight_kg` decimal(10,2) DEFAULT 0.00,
  `current_cbm` decimal(8,4) DEFAULT 0.00,
  `total_cartons` int unsigned NOT NULL DEFAULT 0,
  `total_qty` int unsigned NOT NULL DEFAULT 0,
  `loading_pct` decimal(5,2) DEFAULT 0.00,
  `weight_distribution` varchar(50) DEFAULT 'balanced',
  `truck_plate` varchar(50) DEFAULT NULL,
  `driver_name` varchar(255) DEFAULT NULL,
  `loading_date` date DEFAULT NULL,
  `status` enum('empty','loading','full','sealed','shipped') NOT NULL DEFAULT 'empty',
  `loaded_at` timestamp NULL DEFAULT NULL,
  `sealed_at` timestamp NULL DEFAULT NULL,
  `notes` text 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_container_code` (`container_code`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 12. CONTAINER CARTONS (link table)
CREATE TABLE IF NOT EXISTS `container_cartons` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `container_id` int unsigned NOT NULL,
  `carton_id` int unsigned NOT NULL,
  `pallet_id` int unsigned DEFAULT NULL,
  `position_x` int unsigned DEFAULT 0,
  `position_y` int unsigned DEFAULT 0,
  `position_z` int unsigned DEFAULT 0,
  `loaded_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_container_carton` (`container_id`, `carton_id`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_pallet` (`pallet_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 13. PACKING QUALITY CHECKS
CREATE TABLE IF NOT EXISTS `packing_quality` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `carton_id` int unsigned DEFAULT NULL,
  `packing_order_id` int unsigned NOT NULL,
  `check_type` enum('wrong_size','wrong_color','wrong_barcode','wrong_polybag','wrong_fold','wrong_sticker','wrong_carton','weight_error','label_mismatch','other') NOT NULL,
  `severity` enum('critical','major','minor') NOT NULL DEFAULT 'minor',
  `description` text DEFAULT NULL,
  `detected_by` enum('operator','scanner','camera','ai','inspector') NOT NULL DEFAULT 'operator',
  `status` enum('open','correcting','resolved','dismissed') NOT NULL DEFAULT 'open',
  `resolved_by` int unsigned DEFAULT NULL,
  `resolved_at` timestamp NULL DEFAULT NULL,
  `resolution_notes` text 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`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 14. SHIPPING MARKS
CREATE TABLE IF NOT EXISTS `shipping_marks` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `packing_order_id` int unsigned NOT NULL,
  `mark_type` enum('shipping','carton_number','handling','destination','origin','barcode','qr_code','custom') NOT NULL DEFAULT 'shipping',
  `mark_text` text NOT NULL,
  `mark_position` varchar(100) DEFAULT NULL,
  `print_count` int unsigned NOT NULL DEFAULT 0,
  `status` enum('active','printed') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_packing_order` (`packing_order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 15. PACKING DOCUMENTS
CREATE TABLE IF NOT EXISTS `packing_documents` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `packing_order_id` int unsigned NOT NULL,
  `doc_type` enum('packing_list','carton_list','carton_label','pallet_label','container_plan','shipping_marks','completion_certificate','packing_report','barcode_labels','other') NOT NULL,
  `doc_name` varchar(255) NOT NULL,
  `file_path` varchar(500) DEFAULT NULL,
  `generated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_packing_order` (`packing_order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 16. PACKING AI ANALYSIS
CREATE TABLE IF NOT EXISTS `packing_ai_analysis` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `packing_order_id` int unsigned NOT NULL,
  `analysis_type` enum('carton_optimization','container_loading','shipment_readiness','cost_optimization','weight_distribution') NOT NULL,
  `input_data` json DEFAULT NULL,
  `result_data` json DEFAULT NULL,
  `recommendation` text DEFAULT NULL,
  `efficiency_score` decimal(5,2) DEFAULT NULL,
  `cost_saving_usd` decimal(12,2) DEFAULT NULL,
  `status` enum('pending','completed','applied','dismissed') NOT NULL DEFAULT 'pending',
  `applied_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_type` (`analysis_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 17. PACKING AUDIT LOG
CREATE TABLE IF NOT EXISTS `packing_audit` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `entity_type` varchar(50) NOT NULL,
  `entity_id` int unsigned NOT NULL,
  `action` varchar(50) NOT NULL,
  `old_values` json DEFAULT NULL,
  `new_values` json DEFAULT NULL,
  `performed_by` int unsigned DEFAULT NULL,
  `performed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_entity` (`entity_type`, `entity_id`),
  KEY `idx_performed_at` (`performed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: fix_packing_schema.sql
-- ============================================================

-- ============================================================
-- FIX PACKING SCHEMA — Add missing columns + new tables
-- ============================================================

DELIMITER $$

-- Helper procedure: add column if not exists
CREATE PROCEDURE IF NOT EXISTS add_col_if_missing(
  IN p_table VARCHAR(64),
  IN p_column VARCHAR(64),
  IN p_defn TEXT
)
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = p_table AND COLUMN_NAME = p_column
  ) THEN
    SET @sql = CONCAT('ALTER TABLE `', p_table, '` ADD COLUMN `', p_column, '` ', p_defn);
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  END IF;
END$$

DELIMITER ;

-- ============================================================
-- 1. PACKING_ORDER_LINES — add columns the API needs
-- ============================================================
CALL add_col_if_missing('packing_order_lines', 'po_color_size_id', 'int unsigned DEFAULT NULL AFTER `packing_order_id`');
CALL add_col_if_missing('packing_order_lines', 'size_name', 'varchar(100) DEFAULT NULL AFTER `color`');
CALL add_col_if_missing('packing_order_lines', 'qty', 'int unsigned NOT NULL DEFAULT 0 AFTER `size_name`');
CALL add_col_if_missing('packing_order_lines', 'pieces_per_carton', 'int unsigned DEFAULT NULL AFTER `qty`');
CALL add_col_if_missing('packing_order_lines', 'cartons_planned', 'int unsigned DEFAULT 0 AFTER `pieces_per_carton`');

-- ============================================================
-- 2. PACKING_STATIONS — add columns the API needs
-- ============================================================
CALL add_col_if_missing('packing_stations', 'station_type', "varchar(50) DEFAULT 'general' AFTER `station_name`");
CALL add_col_if_missing('packing_stations', 'max_cartons', 'int unsigned DEFAULT 50 AFTER `has_scanner`');

-- ============================================================
-- 3. PACKING_SESSIONS — add status alias column
-- ============================================================
CALL add_col_if_missing('packing_sessions', 'status', "varchar(20) DEFAULT 'active' AFTER `session_status`");

-- ============================================================
-- 4. PACKING_AI_ANALYSIS — add columns the API needs
-- ============================================================
CALL add_col_if_missing('packing_ai_analysis', 'quality_score', 'decimal(5,2) DEFAULT NULL AFTER `efficiency_score`');
CALL add_col_if_missing('packing_ai_analysis', 'weight_efficiency', 'decimal(5,2) DEFAULT NULL AFTER `quality_score`');
CALL add_col_if_missing('packing_ai_analysis', 'overall_score', 'decimal(5,2) DEFAULT NULL AFTER `weight_efficiency`');
CALL add_col_if_missing('packing_ai_analysis', 'recommendations', 'json DEFAULT NULL AFTER `overall_score`');
CALL add_col_if_missing('packing_ai_analysis', 'analyzed_by', 'int unsigned DEFAULT NULL AFTER `recommendations`');
CALL add_col_if_missing('packing_ai_analysis', 'ai_insights', 'text DEFAULT NULL AFTER `analyzed_by`');
CALL add_col_if_missing('packing_ai_analysis', 'ai_provider', 'varchar(50) DEFAULT NULL AFTER `ai_insights`');
CALL add_col_if_missing('packing_ai_analysis', 'ai_model', 'varchar(100) DEFAULT NULL AFTER `ai_provider`');

-- ============================================================
-- 5. NEW TABLE: packing_instruction_sections
-- ============================================================
CREATE TABLE IF NOT EXISTS `packing_instruction_sections` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `instruction_id` int unsigned NOT NULL,
  `section_title` varchar(255) NOT NULL,
  `section_content` text DEFAULT NULL,
  `sort_order` int unsigned NOT NULL DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_instruction` (`instruction_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 6. NEW TABLE: carton_labels
-- ============================================================
CREATE TABLE IF NOT EXISTS `carton_labels` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `carton_id` int unsigned NOT NULL,
  `packing_order_id` int unsigned NOT NULL,
  `label_type` enum('carton','pallet','shipping','barcode','qr','custom') NOT NULL DEFAULT 'carton',
  `buyer_name` varchar(255) DEFAULT NULL,
  `po_number` varchar(100) DEFAULT NULL,
  `style_no` varchar(100) DEFAULT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size_range` varchar(100) DEFAULT NULL,
  `quantity` int unsigned DEFAULT NULL,
  `destination` varchar(255) DEFAULT NULL,
  `carton_seq` int unsigned DEFAULT NULL,
  `total_cartons` int unsigned DEFAULT NULL,
  `barcode_data` varchar(500) DEFAULT NULL,
  `qr_data` varchar(500) DEFAULT NULL,
  `label_data` json DEFAULT NULL,
  `is_printed` tinyint(1) NOT NULL DEFAULT 0,
  `printed_at` timestamp NULL DEFAULT NULL,
  `printed_count` int unsigned NOT NULL DEFAULT 0,
  `status` enum('generated','printed','void') NOT NULL DEFAULT 'generated',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 7. NEW TABLE: packing_checklists
-- ============================================================
CREATE TABLE IF NOT EXISTS `packing_checklists` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `packing_order_id` int unsigned NOT NULL,
  `carton_id` int unsigned DEFAULT NULL,
  `checklist_type` enum('pre_packing','carton_seal','pallet_build','container_load','shipment_final') NOT NULL DEFAULT 'pre_packing',
  `check_item` varchar(255) NOT NULL,
  `check_result` enum('pass','fail','na') DEFAULT NULL,
  `notes` text DEFAULT NULL,
  `checked_by` int unsigned DEFAULT NULL,
  `checked_at` timestamp NULL DEFAULT NULL,
  `status` enum('pending','checked') NOT NULL DEFAULT 'pending',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_packing_order` (`packing_order_id`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_type` (`checklist_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- 8. PACKING_INSTRUCTIONS — add columns the API references
-- ============================================================
CALL add_col_if_missing('packing_instructions', 'instruction_code', "varchar(50) DEFAULT NULL AFTER `company_id`");
CALL add_col_if_missing('packing_instructions', 'title', "varchar(255) DEFAULT NULL AFTER `instruction_code`");
CALL add_col_if_missing('packing_instructions', 'description', 'text DEFAULT NULL AFTER `title`');
CALL add_col_if_missing('packing_instructions', 'created_by', 'int unsigned DEFAULT NULL AFTER `status`');

-- ============================================================
-- 9. CARTON_LABELS — add missing column
-- ============================================================
CALL add_col_if_missing('carton_labels', 'company_id', 'int unsigned NOT NULL DEFAULT 1 AFTER `id`');

-- ============================================================
-- CLEANUP: drop helper procedure
-- ============================================================
DROP PROCEDURE IF EXISTS add_col_if_missing;


-- ============================================================
-- FILE: fix_packing_phase2.sql
-- ============================================================

-- ============================================================
-- FIX PACKING PHASE 2: Create missing tables
-- ============================================================

-- 1. container_pallets (API references packing_container_pallets but table doesn't exist)
CREATE TABLE IF NOT EXISTS `container_pallets` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `container_id` int unsigned NOT NULL,
  `pallet_id` int unsigned NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_container_pallet` (`container_id`, `pallet_id`),
  KEY `idx_container` (`container_id`),
  KEY `idx_pallet` (`pallet_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 2. carton_barcodes (individual garment barcodes per carton)
CREATE TABLE IF NOT EXISTS `carton_barcodes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `carton_id` int unsigned NOT NULL,
  `carton_item_id` int unsigned DEFAULT NULL,
  `barcode` varchar(255) NOT NULL,
  `garment_sku` varchar(100) DEFAULT NULL,
  `color` varchar(100) DEFAULT NULL,
  `size_name` varchar(50) DEFAULT NULL,
  `status` enum('active','scanned','verified','void') NOT NULL DEFAULT 'active',
  `scanned_at` timestamp NULL DEFAULT NULL,
  `verified_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_barcode` (`barcode`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_item` (`carton_item_id`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 3. carton_qrcodes (QR code data per carton)
CREATE TABLE IF NOT EXISTS `carton_qrcodes` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `carton_id` int unsigned NOT NULL,
  `qr_data` text NOT NULL,
  `qr_type` enum('carton_trace','pallet_trace','container_trace','custom') NOT NULL DEFAULT 'carton_trace',
  `encoded_url` varchar(500) DEFAULT NULL,
  `status` enum('generated','printed','scanned') NOT NULL DEFAULT 'generated',
  `scan_count` int unsigned NOT NULL DEFAULT 0,
  `last_scanned_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_carton` (`carton_id`),
  KEY `idx_type` (`qr_type`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- ============================================================
-- FILE: seed_packing.sql
-- ============================================================

-- ============================================================
-- PACKING MODULE SEED DATA
-- ============================================================

-- Packing Instructions (sample buyer-specific)
INSERT INTO `packing_instructions` (`company_id`, `buyer_id`, `style_id`, `instruction_name`, `fold_type`, `garment_orientation`, `polybag_type`, `polybag_size`, `sticker_position`, `barcode_position`, `size_sticker_required`, `hanger_required`, `carton_type`, `carton_weight_max_kg`, `carton_length_cm`, `carton_width_cm`, `carton_height_cm`, `pieces_per_carton`, `carton_printing`, `shipping_marks`, `special_instructions`, `status`) VALUES
(1, 1, NULL, 'H&M Standard Packing', 'Flat Fold', 'Face Up', 'Self Adhesive', '30x40cm', 'Front Center', 'Right Side', 1, 0, '5 Ply Export', 18.00, 60, 40, 35, 50, '2-color flexo print per H&M spec', 'H&M logo, PO#, Style#, Color, Size, Made in Bangladesh', 'Keep polybag seal on right side', 'active'),
(1, 2, NULL, 'Zara Premium Packing', 'Flat Fold', 'Face Down', 'Self Adhesive', '28x38cm', 'Back Center', 'Left Side', 1, 0, '3 Ply Export', 15.00, 55, 38, 32, 40, 'Single color print per Inditex spec', 'ZARA, PO#, Style#, RN#, Made in Bangladesh', 'Tissue paper between garments', 'active'),
(1, 3, NULL, 'Nike Sustainble Packing', 'Rolled', 'Face Up', 'Recycled Poly', '32x42cm', 'Front Right', 'Inside Polybag', 1, 0, 'Corrugated Recycled', 20.00, 65, 45, 40, 48, 'Eco-label required per Nike RSL', 'Nike swoosh, PO#, Style#, Color code, Size, Country of origin', 'Use Nike sustainable poly only', 'active'),
(1, 4, NULL, 'Adidas Packing Spec', 'Flat Fold', 'Face Up', 'Self Adhesive', '30x40cm', 'Front Center', 'Back Side', 1, 0, '5 Ply Export', 18.00, 60, 42, 35, 50, '2-color per Adidas spec', 'Adidas logo, PO#, Style#, Size, Barcode', 'Fold per Adidas visual guide', 'active'),
(1, 5, NULL, 'Uniqlo Standard', 'Flat Fold', 'Face Up', 'Self Adhesive', '25x35cm', 'Center', 'Front', 0, 0, '3 Ply Standard', 12.00, 50, 35, 30, 60, 'Simple black print', 'UNIQLO, PO#, Style#, Size', 'Vacuum pack for down items', 'active');

-- Packing Stations
INSERT INTO `packing_stations` (`company_id`, `station_code`, `station_name`, `factory_id`, `location`, `has_scale`, `has_camera`, `has_printer`, `has_scanner`, `status`) VALUES
(1, 'PS-01', 'Packing Station 1', NULL, 'Packing Floor - Zone A', 1, 1, 1, 1, 'active'),
(1, 'PS-02', 'Packing Station 2', NULL, 'Packing Floor - Zone A', 1, 1, 1, 1, 'active'),
(1, 'PS-03', 'Packing Station 3', NULL, 'Packing Floor - Zone B', 1, 0, 1, 1, 'active'),
(1, 'PS-04', 'Packing Station 4', NULL, 'Packing Floor - Zone B', 1, 1, 1, 1, 'active'),
(1, 'PS-05', 'Packing Station 5', NULL, 'Packing Floor - Zone C', 1, 0, 1, 1, 'active'),
(1, 'PS-06', 'Packing Station 6', NULL, 'Packing Floor - Zone C', 1, 1, 1, 1, 'active'),
(1, 'PS-QC', 'QC Packing Station', NULL, 'QC Area', 1, 1, 1, 1, 'active'),
(1, 'PS-SP', 'Special Packing', NULL, 'Premium Zone', 1, 1, 1, 1, 'active');

-- Packing Orders (auto-generated from existing Buyer POs)
INSERT INTO `packing_orders` (`company_id`, `packing_order_code`, `buyer_po_id`, `buyer_id`, `style_id`, `factory_id`, `total_qty`, `total_cartons_planned`, `total_cartons_packed`, `total_pieces_packed`, `pieces_per_carton`, `destination`, `shipment_date`, `etd`, `eta`, `shipment_mode`, `status`, `packing_started_at`, `packing_accuracy`, `notes`) VALUES
(1, 'PKO-2026-0001', 1, 1, 1, NULL, 12000, 240, 240, 12000, 50, 'Germany', '2026-08-15', '2026-08-20', '2026-09-15', 'sea', 'verified', '2026-07-01 08:00:00', 99.92, 'H&M order - completed and verified'),
(1, 'PKO-2026-0002', 2, 1, 2, NULL, 8000, 200, 180, 7200, 40, 'Sweden', '2026-09-01', '2026-09-05', '2026-10-01', 'sea', 'in_progress', '2026-07-10 08:00:00', NULL, 'H&M second order - packing in progress'),
(1, 'PKO-2026-0003', 3, 2, 3, NULL, 5000, 125, 0, 0, 40, 'Spain', '2026-10-10', '2026-10-15', '2026-11-10', 'sea', 'pending', NULL, NULL, 'Zara order - pending start'),
(1, 'PKO-2026-0004', 6, 3, 6, NULL, 10000, 209, 45, 2160, 48, 'USA', '2026-08-25', '2026-08-30', '2026-09-20', 'sea', 'in_progress', '2026-07-15 08:00:00', NULL, 'Nike eco order - packing started'),
(1, 'PKO-2026-0005', 4, 3, 4, NULL, 15000, 300, 0, 0, 50, 'Netherlands', '2026-09-15', '2026-09-20', '2026-10-15', 'sea', 'pending', NULL, NULL, 'Nike big order - awaiting materials');

-- Packing Order Lines
INSERT INTO `packing_order_lines` (`packing_order_id`, `color`, `size`, `quantity`, `quantity_packed`, `quantity_remaining`) VALUES
(1, 'Black', 'S', 2000, 2000, 0),
(1, 'Black', 'M', 2500, 2500, 0),
(1, 'Black', 'L', 2500, 2500, 0),
(1, 'Black', 'XL', 1500, 1500, 0),
(1, 'White', 'S', 800, 800, 0),
(1, 'White', 'M', 1200, 1200, 0),
(1, 'White', 'L', 1000, 1000, 0),
(1, 'White', 'XL', 500, 500, 0),
(2, 'Navy', 'S', 1200, 1100, 100),
(2, 'Navy', 'M', 1800, 1700, 100),
(2, 'Navy', 'L', 1800, 1600, 200),
(2, 'Navy', 'XL', 1200, 1000, 200),
(2, 'Grey', 'S', 800, 700, 100),
(2, 'Grey', 'M', 1200, 1100, 100),
(3, 'Red', 'XS', 500, 0, 500),
(3, 'Red', 'S', 800, 0, 800),
(3, 'Red', 'M', 1200, 0, 1200),
(3, 'Red', 'L', 1200, 0, 1200),
(3, 'Red', 'XL', 800, 0, 800),
(3, 'Red', 'XXL', 500, 0, 500),
(4, 'Black', 'S', 1600, 400, 1200),
(4, 'Black', 'M', 2400, 800, 1600),
(4, 'Black', 'L', 2400, 600, 1800),
(4, 'Black', 'XL', 1600, 360, 1240),
(5, 'White', 'S', 2000, 0, 2000),
(5, 'White', 'M', 3000, 0, 3000),
(5, 'White', 'L', 3000, 0, 3000),
(5, 'White', 'XL', 2000, 0, 2000),
(5, 'Black', 'S', 1200, 0, 1200),
(5, 'Black', 'M', 1800, 0, 1800),
(5, 'Black', 'L', 1200, 0, 1200),
(5, 'Black', 'XL', 800, 0, 800);

-- Cartons (for completed and in-progress orders)
-- PKO-0001 (H&M - all 240 cartons)
INSERT INTO `cartons` (`company_id`, `carton_code`, `packing_order_id`, `session_id`, `carton_seq`, `total_qty`, `weight_kg`, `length_cm`, `width_cm`, `height_cm`, `cbm`, `color`, `size_range`, `is_mixed`, `is_sealed`, `label_printed`, `status`, `packed_at`, `sealed_at`)
SELECT 1, CONCAT('CTN-2026-0001-', LPAD(n, 3, '0')), 1, NULL, n, 50,
  16.50 + (RAND() * 2), 60, 40, 35, 0.0840,
  CASE WHEN n <= 40 THEN 'Black' WHEN n <= 50 THEN 'White' ELSE 'Black' END,
  CASE WHEN n <= 24 THEN 'S-M' WHEN n <= 44 THEN 'M-L' ELSE 'L-XL' END,
  0, 1, 1, 'shipped',
  '2026-07-05 10:00:00', '2026-07-05 10:15:00'
FROM (
  SELECT a.N + b.N * 10 + 1 AS n
  FROM (SELECT 0 AS N UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) a,
       (SELECT 0 AS N UNION SELECT 1 UNION SELECT 2) b
) nums WHERE n <= 240;

-- PKO-0002 (H&M in-progress - 180 cartons)
INSERT INTO `cartons` (`company_id`, `carton_code`, `packing_order_id`, `carton_seq`, `total_qty`, `weight_kg`, `length_cm`, `width_cm`, `height_cm`, `cbm`, `color`, `is_mixed`, `is_sealed`, `label_printed`, `status`, `packed_at`)
SELECT 1, CONCAT('CTN-2026-0002-', LPAD(n, 3, '0')), 2, n, 40,
  13.00 + (RAND() * 1.5), 55, 38, 32, 0.0669,
  CASE WHEN n % 3 = 0 THEN 'Grey' ELSE 'Navy' END,
  0, 1, 1, 'packed',
  '2026-07-18 09:00:00'
FROM (
  SELECT a.N + b.N * 10 + 1 AS n
  FROM (SELECT 0 AS N UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) a,
       (SELECT 0 AS N UNION SELECT 1) b
) nums WHERE n <= 180;

-- PKO-0004 (Nike - 45 cartons packed so far)
INSERT INTO `cartons` (`company_id`, `carton_code`, `packing_order_id`, `carton_seq`, `total_qty`, `weight_kg`, `length_cm`, `width_cm`, `height_cm`, `cbm`, `color`, `is_mixed`, `is_sealed`, `label_printed`, `status`, `packed_at`)
SELECT 1, CONCAT('CTN-2026-0004-', LPAD(n, 3, '0')), 4, n, 48,
  17.00 + (RAND() * 2), 65, 45, 40, 0.1170,
  'Black', 0, 1, 1, 'packed',
  '2026-07-20 08:00:00'
FROM (
  SELECT a.N + b.N * 10 + 1 AS n
  FROM (SELECT 0 AS N UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) a,
       (SELECT 0 AS N) b
) nums WHERE n <= 45;

-- Carton Items (sample for first few cartons)
INSERT INTO `carton_items` (`carton_id`, `packing_order_line_id`, `color`, `size`, `quantity`, `barcode`) VALUES
(1, 1, 'Black', 'S', 50, 'BLK-S-0001'),
(2, 1, 'Black', 'S', 50, 'BLK-S-0002'),
(3, 1, 'Black', 'S', 50, 'BLK-S-0003'),
(4, 1, 'Black', 'S', 50, 'BLK-S-0004'),
(5, 2, 'Black', 'M', 50, 'BLK-M-0005'),
(6, 2, 'Black', 'M', 50, 'BLK-M-0006'),
(7, 2, 'Black', 'M', 50, 'BLK-M-0007'),
(8, 2, 'Black', 'M', 50, 'BLK-M-0008'),
(9, 2, 'Black', 'M', 50, 'BLK-M-0009'),
(10, 3, 'Black', 'L', 50, 'BLK-L-0010'),
(11, 3, 'Black', 'L', 50, 'BLK-L-0011'),
(12, 3, 'Black', 'L', 50, 'BLK-L-0012'),
(13, 3, 'Black', 'L', 50, 'BLK-L-0013'),
(14, 3, 'Black', 'L', 50, 'BLK-L-0014'),
(15, 4, 'Black', 'XL', 50, 'BLK-XL-0015'),
(16, 4, 'Black', 'XL', 50, 'BLK-XL-0016'),
(17, 4, 'Black', 'XL', 50, 'BLK-XL-0017'),
(18, 5, 'White', 'S', 50, 'WHT-S-0018'),
(19, 5, 'White', 'S', 50, 'WHT-S-0019'),
(20, 6, 'White', 'M', 50, 'WHT-M-0020'),
(21, 6, 'White', 'M', 50, 'WHT-M-0021'),
(22, 7, 'White', 'L', 50, 'WHT-L-0022'),
(23, 7, 'White', 'L', 50, 'WHT-L-0023'),
(24, 8, 'White', 'XL', 50, 'WHT-XL-0024');

-- Pallets (for completed order PKO-0001)
INSERT INTO `pallets` (`company_id`, `pallet_code`, `packing_order_id`, `total_cartons`, `total_qty`, `weight_kg`, `height_cm`, `length_cm`, `width_cm`, `cbm`, `is_stacked`, `is_wrapped`, `ai_load_balance`, `status`, `completed_at`) VALUES
(1, 'PALL-001', 1, 20, 1000, 340.50, 180, 120, 100, 2.1600, 1, 1, 'balanced', 'loaded', '2026-07-06 14:00:00'),
(1, 'PALL-002', 1, 20, 1000, 338.20, 175, 120, 100, 2.1000, 1, 1, 'balanced', 'loaded', '2026-07-06 14:30:00'),
(1, 'PALL-003', 1, 20, 1000, 342.80, 182, 120, 100, 2.1840, 1, 1, 'slightly_front_heavy', 'loaded', '2026-07-06 15:00:00'),
(1, 'PALL-004', 1, 20, 1000, 335.60, 178, 120, 100, 2.1360, 1, 1, 'balanced', 'loaded', '2026-07-06 15:30:00'),
(1, 'PALL-005', 1, 20, 1000, 341.20, 180, 120, 100, 2.1600, 1, 1, 'balanced', 'loaded', '2026-07-06 16:00:00'),
(1, 'PALL-006', 1, 20, 1000, 339.80, 177, 120, 100, 2.1240, 1, 1, 'balanced', 'loaded', '2026-07-06 16:30:00'),
(1, 'PALL-007', 1, 20, 1000, 344.10, 183, 120, 100, 2.1960, 1, 1, 'balanced', 'loaded', '2026-07-06 17:00:00'),
(1, 'PALL-008', 1, 20, 1000, 336.90, 176, 120, 100, 2.1120, 1, 1, 'balanced', 'loaded', '2026-07-06 17:30:00'),
(1, 'PALL-009', 1, 20, 1000, 340.00, 180, 120, 100, 2.1600, 1, 1, 'balanced', 'loaded', '2026-07-07 08:00:00'),
(1, 'PALL-010', 1, 20, 1000, 337.50, 178, 120, 100, 2.1360, 1, 1, 'balanced', 'loaded', '2026-07-07 08:30:00'),
(1, 'PALL-011', 1, 20, 1000, 341.00, 181, 120, 100, 2.1720, 1, 1, 'balanced', 'loaded', '2026-07-07 09:00:00'),
(1, 'PALL-012', 1, 20, 1000, 338.80, 179, 120, 100, 2.1480, 1, 1, 'balanced', 'loaded', '2026-07-07 09:30:00');

-- Containers (for verified order PKO-0001)
INSERT INTO `packing_containers` (`company_id`, `container_code`, `container_number`, `container_type`, `packing_order_id`, `seal_number`, `max_weight_kg`, `max_cbm`, `current_weight_kg`, `current_cbm`, `total_cartons`, `total_qty`, `loading_pct`, `weight_distribution`, `truck_plate`, `driver_name`, `loading_date`, `status`, `loaded_at`, `sealed_at`) VALUES
(1, 'CNT-001', 'MSCU-4567890', '40ft', 1, 'SEAL-2026-001', 26000, 67.70, 18250.00, 43.20, 120, 6000, 63.81, 'balanced', 'DHK-12345', 'Mohammed Rahman', '2026-07-08', 'sealed', '2026-07-08 08:00:00', '2026-07-08 14:00:00'),
(1, 'CNT-002', 'MSCU-4567891', '40ft', 1, 'SEAL-2026-002', 26000, 67.70, 17920.00, 41.50, 120, 6000, 61.30, 'balanced', 'DHK-12346', 'Kamal Ahmed', '2026-07-08', 'sealed', '2026-07-08 14:30:00', '2026-07-08 18:00:00');

-- Container Cartons (link first 120 cartons to containers)
INSERT INTO `container_cartons` (`container_id`, `carton_id`, `pallet_id`, `position_x`, `position_y`, `position_z`)
SELECT 1, c.id, p.id,
  FLOOR((c.carton_seq - 1) / 20) AS px,
  FLOOR(((c.carton_seq - 1) % 20) / 5) AS py,
  (c.carton_seq - 1) % 5 AS pz
FROM cartons c
JOIN pallets p ON p.packing_order_id = c.packing_order_id AND p.id <= 6
WHERE c.packing_order_id = 1 AND c.carton_seq <= 120
ORDER BY c.carton_seq;

INSERT INTO `container_cartons` (`container_id`, `carton_id`, `pallet_id`, `position_x`, `position_y`, `position_z`)
SELECT 2, c.id, p.id,
  FLOOR((c.carton_seq - 121) / 20) AS px,
  FLOOR(((c.carton_seq - 121) % 20) / 5) AS py,
  (c.carton_seq - 121) % 5 AS pz
FROM cartons c
JOIN pallets p ON p.packing_order_id = c.packing_order_id AND p.id >= 7
WHERE c.packing_order_id = 1 AND c.carton_seq > 120 AND c.carton_seq <= 240
ORDER BY c.carton_seq;

-- Packing Quality Issues
INSERT INTO `packing_quality` (`company_id`, `carton_id`, `packing_order_id`, `check_type`, `severity`, `description`, `detected_by`, `status`, `resolved_at`, `resolution_notes`) VALUES
(1, 25, 2, 'wrong_size', 'major', 'Size M packed in Size L carton - CTN-0002-0025', 'scanner', 'resolved', '2026-07-18 14:00:00', 'Garment removed and re-sorted'),
(1, 88, 2, 'weight_error', 'minor', 'Carton weight 14.2kg exceeds mixed tolerance', 'operator', 'resolved', '2026-07-19 10:00:00', 'One piece removed, weight now 12.8kg'),
(1, 156, 2, 'wrong_barcode', 'critical', 'Barcode mismatch - garment barcode belongs to different PO', 'scanner', 'open', NULL, NULL),
(1, NULL, 4, 'wrong_polybag', 'minor', 'Nike sustainable polybag not used - standard poly applied', 'camera', 'open', NULL, NULL),
(1, 200, 4, 'wrong_fold', 'minor', 'Garment folded flat instead of rolled per Nike spec', 'ai', 'correcting', NULL, 'Re-folding in progress');

-- Shipping Marks
INSERT INTO `shipping_marks` (`company_id`, `packing_order_id`, `mark_type`, `mark_text`, `mark_position`, `status`) VALUES
(1, 1, 'shipping', 'H&M Hennes & Mauritz AB\nSödra Hamnvägen 6B\nSE-251 08 Helsingborg\nSweden', 'All sides', 'printed'),
(1, 1, 'carton_number', 'CTN NO: {carton_seq} / {total_cartons}\nSTYLE: {style_no}\nCOLOR: {color}\nSIZE: {size}\nQTY: {qty}\nGW: {weight} KG', 'Front face', 'printed'),
(1, 1, 'handling', 'THIS SIDE UP\nFRAGILE\nKEEP DRY\nDO NOT STACK MORE THAN 3 HIGH', 'All sides', 'printed'),
(1, 1, 'origin', 'MADE IN BANGLADESH', 'Right side', 'printed'),
(1, 2, 'shipping', 'H&M Hennes & Mauritz AB\nSödra Hamnvägen 6B\nSE-251 08 Helsingborg\nSweden', 'All sides', 'active'),
(1, 3, 'shipping', 'ZARA / INDITEX\nAvenida de la Diputación s/n\n15143 Arteixo, Spain', 'All sides', 'active'),
(1, 4, 'shipping', 'NIKE Inc.\nOne Bowerman Drive\nBeaverton, OR 97005, USA', 'All sides', 'active');

-- Packing AI Analysis
INSERT INTO `packing_ai_analysis` (`company_id`, `packing_order_id`, `analysis_type`, `result_data`, `recommendation`, `efficiency_score`, `cost_saving_usd`, `status`) VALUES
(1, 1, 'carton_optimization', '{"suggested_ppc": 50, "optimized_cartons": 240, "mixed_cartons": 0, "wasted_space_pct": 2.1}', 'Standard 50ppc is optimal for this order. No mixed cartons needed.', 97.90, 1250.00, 'applied'),
(1, 1, 'container_loading', '{"utilization_pct": 92.3, "cartons_per_container": 120, "containers_needed": 2, "weight_balanced": true}', 'Two 40ft containers with balanced loading. Weight distribution is optimal.', 92.30, 3200.00, 'applied'),
(1, 2, 'carton_optimization', '{"suggested_ppc": 40, "optimized_cartons": 200, "mixed_cartons": 2, "wasted_space_pct": 3.8}', 'Use 198 standard cartons + 2 mixed cartons for remaining pieces.', 96.20, 480.00, 'completed'),
(1, 4, 'carton_optimization', '{"suggested_ppc": 48, "optimized_cartons": 209, "mixed_cartons": 5, "wasted_space_pct": 4.2}', 'Nike order: Use 48ppc standard. 5 mixed cartons for size/color remainders.', 95.80, 890.00, 'completed'),
(1, 4, 'shipment_readiness', '{"packing_pct": 10.3, "labels_pct": 10.3, "pallet_pct": 0, "container_pct": 0, "docs_pct": 0, "overall": 10.3}', 'Early stage. Focus on completing carton packing before palletizing.', 10.30, NULL, 'completed');

-- Packing Documents
INSERT INTO `packing_documents` (`company_id`, `packing_order_id`, `doc_type`, `doc_name`) VALUES
(1, 1, 'packing_list', 'Packing List - PKO-2026-0001 - H&M'),
(1, 1, 'carton_list', 'Carton List - PKO-2026-0001 - 240 Cartons'),
(1, 1, 'carton_label', 'Carton Labels - PKO-2026-0001'),
(1, 1, 'pallet_label', 'Pallet Labels - PKO-2026-0001 - 12 Pallets'),
(1, 1, 'container_plan', 'Container Loading Plan - PKO-2026-0001'),
(1, 1, 'shipping_marks', 'Shipping Marks - PKO-2026-0001'),
(1, 1, 'completion_certificate', 'Packing Completion Certificate - PKO-2026-0001'),
(1, 1, 'packing_report', 'Packing Report - PKO-2026-0001');


-- ============================================================
-- END OF FULL SETUP
-- Total tables: ~150+
-- ============================================================
