-- Migration: Add arrival tracking fields to emergency_responses
-- Run this to add arrival tracking for donors
-- IMPORTANT: Run this SQL file in your database before using the arrival feature

USE `blood_bank`;

-- Check if columns already exist before adding
SET @dbname = DATABASE();
SET @tablename = 'emergency_responses';
SET @columnname1 = 'arrived_at';
SET @columnname2 = 'arrival_notes';

SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (COLUMN_NAME = @columnname1)
  ) > 0,
  'SELECT 1', -- Column exists, do nothing
  CONCAT('ALTER TABLE `', @tablename, '` ADD COLUMN `', @columnname1, '` datetime DEFAULT NULL AFTER `accepted_at`')
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (TABLE_SCHEMA = @dbname)
      AND (TABLE_NAME = @tablename)
      AND (COLUMN_NAME = @columnname2)
  ) > 0,
  'SELECT 1', -- Column exists, do nothing
  CONCAT('ALTER TABLE `', @tablename, '` ADD COLUMN `', @columnname2, '` text DEFAULT NULL AFTER `arrived_at`')
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

-- Alternative simple version (uncomment if the above doesn't work):
-- ALTER TABLE `emergency_responses` 
-- ADD COLUMN IF NOT EXISTS `arrived_at` datetime DEFAULT NULL AFTER `accepted_at`,
-- ADD COLUMN IF NOT EXISTS `arrival_notes` text DEFAULT NULL AFTER `arrived_at`;
