CREATE TABLE IF NOT EXISTS contact_links (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  label_ar VARCHAR(120) NOT NULL,
  label_en VARCHAR(120) NULL,
  type VARCHAR(40) NOT NULL DEFAULT 'link',
  value VARCHAR(255) NOT NULL,
  url VARCHAR(255) NOT NULL,
  icon VARCHAR(40) NOT NULL DEFAULT 'link',
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  sort_order INT NOT NULL DEFAULT 0,
  created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

INSERT IGNORE INTO permissions (permission_key, permission_name, module) VALUES
('view_contact_links','View contact links','contact_links'),
('create_contact_links','Create contact links','contact_links'),
('edit_contact_links','Edit contact links','contact_links'),
('delete_contact_links','Delete contact links','contact_links');

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT 1, id FROM permissions WHERE permission_key IN ('view_contact_links','create_contact_links','edit_contact_links','delete_contact_links');

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT 2, id FROM permissions WHERE permission_key IN ('view_contact_links','create_contact_links','edit_contact_links','delete_contact_links');

INSERT INTO contact_links (label_ar, label_en, type, value, url, icon, is_active, sort_order, created_at, updated_at)
SELECT 'البريد الإلكتروني', 'Email', 'email', COALESCE((SELECT setting_value FROM settings WHERE setting_key='site_email' LIMIT 1), 'info@4tiify.com'), CONCAT('mailto:', COALESCE((SELECT setting_value FROM settings WHERE setting_key='site_email' LIMIT 1), 'info@4tiify.com')), 'email', 1, 1, NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM contact_links LIMIT 1);

INSERT INTO contact_links (label_ar, label_en, type, value, url, icon, is_active, sort_order, created_at, updated_at)
SELECT 'طلب خدمة', 'Request service', 'link', '/request.php', '/request.php', 'link', 1, 2, NOW(), NOW()
WHERE (SELECT COUNT(*) FROM contact_links) = 1;
