-- Check if backup_schedules table exists and update it to new structure
USE whp;

SET @table_exists = (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'whp' AND table_name = 'backup_schedules');

-- If table exists with old structure, drop it and recreate with new structure
-- This is safe for development/testing but in production you'd want to migrate data
DROP TABLE IF EXISTS backup_schedules;

-- Create backup schedules table with new structure
CREATE TABLE IF NOT EXISTS backup_schedules (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user VARCHAR(255) NOT NULL,
    target_id INT NOT NULL,
    backup_type ENUM('site', 'userfiles', 'database') NOT NULL,
    resource_name VARCHAR(255) DEFAULT NULL, -- site domain or database name
    schedule_type ENUM('daily', 'weekly', 'monthly') NOT NULL,
    schedule_time TIME NOT NULL DEFAULT '02:00:00',
    schedule_day INT DEFAULT NULL, -- 0=Sunday, 1=Monday, etc. for weekly; 1-31 for monthly
    max_retention INT NOT NULL DEFAULT 30, -- max number of backups to keep
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    last_run_at TIMESTAMP NULL,
    next_run_at TIMESTAMP NULL,
    INDEX idx_user (user),
    INDEX idx_target_id (target_id),
    INDEX idx_next_run (next_run_at, is_active),
    FOREIGN KEY (target_id) REFERENCES backup_targets(id) ON DELETE CASCADE
);

-- Update next_run_at for existing schedules
UPDATE backup_schedules 
SET next_run_at = CASE 
    WHEN schedule_type = 'daily' THEN 
        DATE_ADD(CURDATE(), INTERVAL 1 DAY) + INTERVAL HOUR(schedule_time) HOUR + INTERVAL MINUTE(schedule_time) MINUTE
    WHEN schedule_type = 'weekly' THEN 
        DATE_ADD(CURDATE(), INTERVAL (7 - WEEKDAY(CURDATE()) + IFNULL(schedule_day, 0)) % 7 DAY) + INTERVAL HOUR(schedule_time) HOUR + INTERVAL MINUTE(schedule_time) MINUTE
    WHEN schedule_type = 'monthly' THEN 
        DATE_ADD(LAST_DAY(CURDATE()), INTERVAL 1 DAY) + INTERVAL (IFNULL(schedule_day, 1) - 1) DAY + INTERVAL HOUR(schedule_time) HOUR + INTERVAL MINUTE(schedule_time) MINUTE
END
WHERE next_run_at IS NULL;