-- WHMCS Ticket Hub schema
-- MySQL / MariaDB

CREATE TABLE IF NOT EXISTS users (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(190) NOT NULL UNIQUE,
  name VARCHAR(190) NOT NULL,
  role ENUM('admin','agent') NOT NULL DEFAULT 'agent',
  password_hash VARCHAR(255) NOT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS brands (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(190) NOT NULL,
  api_url VARCHAR(255) NOT NULL,
  api_identifier_enc TEXT NOT NULL,
  api_secret_enc TEXT NOT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS user_brand_access (
  user_id INT UNSIGNED NOT NULL,
  brand_id INT UNSIGNED NOT NULL,
  PRIMARY KEY (user_id, brand_id),
  CONSTRAINT fk_uba_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_uba_brand FOREIGN KEY (brand_id) REFERENCES brands(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS canned_messages (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  brand_id INT UNSIGNED NULL,
  title VARCHAR(190) NOT NULL,
  body MEDIUMTEXT NOT NULL,
  created_at DATETIME NULL,
  CONSTRAINT fk_cm_brand FOREIGN KEY (brand_id) REFERENCES brands(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seed admin user: admin@example.com / admin123
-- Password hash generated using PHP password_hash (bcrypt/argon2 depending on PHP).
INSERT INTO users (email,name,role,password_hash,is_active,created_at)
VALUES ('admin@example.com','Admin','admin','$2y$10$Zq0sNLrWlH0Hk2GfH88K1uYdQ9pFpsp1iNq2r6H9F8Kc.1H3l0F8a',1,NOW())
ON DUPLICATE KEY UPDATE email=email;

-- Note: no brands are seeded because each WHMCS brand needs its own API credentials.
