-- Phase 21: Appointment role permissions
-- Admin/Super Admin/reception-style users create and manage appointments.
-- Therapists only view their schedule and mark their own appointments completed/no-show.
INSERT INTO permissions (name,display_name) VALUES
 ('appointments.status','Update appointment attendance status')
ON DUPLICATE KEY UPDATE display_name=VALUES(display_name);

INSERT IGNORE INTO role_permissions (role_id,permission_id)
SELECT r.id,p.id FROM roles r JOIN permissions p
WHERE r.name IN ('SUPER_ADMIN','ADMIN') AND p.name IN ('appointments.view','appointments.create','appointments.edit','appointments.status');

INSERT IGNORE INTO role_permissions (role_id,permission_id)
SELECT r.id,p.id FROM roles r JOIN permissions p
WHERE r.name='THERAPIST' AND p.name IN ('appointments.view','appointments.status');

DELETE rp FROM role_permissions rp
JOIN roles r ON r.id=rp.role_id
JOIN permissions p ON p.id=rp.permission_id
WHERE r.name='THERAPIST' AND p.name IN ('appointments.create','appointments.edit');
