-- SheListens — migration 005: admin account controls + platform settings
-- Run via phpMyAdmin or: mysql -u USER -p DBNAME < migrations/005_user_admin_controls.sql
-- Safe to run on an existing database.

ALTER TABLE users
  ADD COLUMN IF NOT EXISTS suspended_at DATETIME NULL AFTER last_login_at;

-- Defaults for the new admin-editable booking/platform settings. Harmless
-- no-ops if a value already exists (the app falls back to hardcoded
-- defaults anyway when a row is missing, but seeding them means they show
-- up in the admin Settings screen right away).
INSERT IGNORE INTO platform_settings (setting_key, setting_value) VALUES
  ('max_sessions_per_day', '3'),
  ('session_minutes', '45'),
  ('booking_buffer_minutes', '15'),
  ('video_fee', '15000'),
  ('maintenance_mode', '0');

-- Ties a payment to the booking it paid for (video session fees). NULL for
-- subscription payments, which are already linked via subscription_id.
ALTER TABLE payments
  ADD COLUMN IF NOT EXISTS booking_id CHAR(36) NULL AFTER subscription_id;

-- Only add the foreign key if it isn't already there (re-running this
-- migration on a DB where it already succeeded shouldn't error out).
SET @fk_exists = (
  SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
  WHERE CONSTRAINT_SCHEMA = DATABASE()
    AND TABLE_NAME = 'payments'
    AND CONSTRAINT_NAME = 'fk_payments_booking'
);
SET @sql = IF(@fk_exists = 0,
  'ALTER TABLE payments ADD CONSTRAINT fk_payments_booking FOREIGN KEY (booking_id) REFERENCES bookings(id) ON DELETE SET NULL',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
