-- ============================================================
-- License Management System — Database Schema
-- ============================================================

CREATE TABLE IF NOT EXISTS admin_users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) UNIQUE NOT NULL,
  password VARCHAR(255) NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(150) NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS licenses (
  id INT AUTO_INCREMENT PRIMARY KEY,
  license_key VARCHAR(64) UNIQUE NOT NULL,
  product_id INT NULL,
  user_email VARCHAR(150) NULL,
  customer_name VARCHAR(150) NULL,
  customer_email VARCHAR(150) NULL,
  allowed_domains TEXT NULL,
  domain_limit INT NOT NULL DEFAULT 1,
  status ENUM('active','expired','suspended') NOT NULL DEFAULT 'active',
  expires_at DATE NULL,
  notes TEXT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS license_activations (
  id INT AUTO_INCREMENT PRIMARY KEY,
  license_id INT NOT NULL,
  domain VARCHAR(255) NOT NULL,
  activated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  last_check DATETIME NULL,
  UNIQUE KEY uniq_license_domain (license_id, domain),
  FOREIGN KEY (license_id) REFERENCES licenses(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS settings (
  skey VARCHAR(100) PRIMARY KEY,
  svalue TEXT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Default settings (change the api_secret after install!)
INSERT INTO settings (skey, svalue) VALUES
  ('api_secret', 'CHANGE_THIS_SECRET_AFTER_INSTALL')
ON DUPLICATE KEY UPDATE svalue = svalue;

-- Sample product
INSERT INTO products (name) VALUES ('Developer License');

-- NOTE: The admin user is created by running install.php in your browser
-- (it safely hashes the password you choose). Do NOT insert admin_users here.
