-- Create roles table
CREATE TABLE IF NOT EXISTS roles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL UNIQUE,
    slug VARCHAR(50) NOT NULL UNIQUE,
    permissions TEXT NULL, -- JSON or serialized array of permissions
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create users table
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    role_id INT NOT NULL,
    active TINYINT(1) DEFAULT 1,
    last_login DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Seed Roles
INSERT IGNORE INTO roles (name, slug, permissions) VALUES 
('Administrator', 'admin', '*'),
('Doctor', 'doctor', '["dashboard", "patients", "visits", "appointments", "home_visits", "reports"]'),
('Nurse', 'nurse', '["dashboard", "patients", "visits", "queue"]'),
('Receptionist', 'receptionist', '["dashboard", "patients", "appointments", "queue", "billing"]'),
('Laboratorial', 'laboratorial', '["dashboard", "laboratory"]'),
('Radiologic', 'radiologic', '["dashboard", "xray"]');

-- Seed Default Admin User (password: admin123)
-- Using a simple hash for demonstration if PHP's password_hash is not available in SQL, 
-- but ideally we should insert via PHP. For now, I will insert a placeholder and update it via PHP or assume I can use a known hash.
-- Hash for 'admin123' (bcrypt)
INSERT IGNORE INTO users (name, email, password, role_id) 
SELECT 'System Admin', 'admin@hospital.com', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', id 
FROM roles WHERE slug = 'admin' LIMIT 1;
