-- Fix appointments table schema: Add start_time/end_time if missing
-- This handles the case where init_db.php created the table with appointment_date instead of start_time

-- Add start_time if it doesn't exist
-- Note: MySQL/MariaDB < 10.2 don't support ADD COLUMN IF NOT EXISTS easily, so we use a stored procedure or just suppress errors in apply_migrations.php
-- Assuming MariaDB 10.2+ or suppression in apply_migrations.php for "Duplicate column"

ALTER TABLE appointments ADD COLUMN start_time DATETIME NULL;
ALTER TABLE appointments ADD COLUMN end_time DATETIME NULL;

-- Migrate data if appointment_date exists
-- Check if appointment_date exists first? SQL doesn't have conditional logic outside procedures easily.
-- We'll try to update, if column doesn't exist it will fail but that's fine if start_time is already populated.
-- Wait, if appointment_date doesn't exist, this query will fail and might stop migration script if not handled.
-- But apply_migrations.php continues on error? No, it catches exceptions per statement.

-- We can wrap in a procedure to be safe, but apply_migrations.php splits by ';'.
-- So let's just try the update. If appointment_date doesn't exist, it fails harmlessly.

UPDATE appointments SET start_time = appointment_date WHERE start_time IS NULL;
UPDATE appointments SET end_time = DATE_ADD(start_time, INTERVAL 30 MINUTE) WHERE end_time IS NULL AND start_time IS NOT NULL;

-- Make start_time NOT NULL after populating
ALTER TABLE appointments MODIFY COLUMN start_time DATETIME NOT NULL;
ALTER TABLE appointments MODIFY COLUMN end_time DATETIME NOT NULL;

-- Drop appointment_date if it exists (optional cleanup)
-- ALTER TABLE appointments DROP COLUMN appointment_date;
