-- =====================================================================
--  ORBIT Website-to-App Builder — Full Database Schema
--  Engine: MySQL 8.0+ / MariaDB 10.5+   Charset: utf8mb4
--  Import via phpMyAdmin (Import tab) or:  mysql -u USER -p DBNAME < schema.sql
--
--  Conventions
--  - All money is stored in KOBO (BIGINT). ₦1,500.00 = 150000. Never use FLOAT for money.
--  - Timestamps are DATETIME in UTC; convert to Africa/Lagos in PHP for display.
--  - Secrets (keystore files/passwords, Apple keys, Firebase keys) are stored
--    ENCRYPTED by PHP (libsodium secretbox) — the DB only ever holds
--    nonce+ciphertext (the 24-byte nonce is stored at the start of each value). The encryption key lives in a config file
--    OUTSIDE the web root, never in this database.
-- =====================================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ---------------------------------------------------------------------
-- 1. USERS & AUTH
-- ---------------------------------------------------------------------

CREATE TABLE users (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  uuid               CHAR(36)        NOT NULL,                 -- public ID used in URLs
  full_name          VARCHAR(120)    NOT NULL,
  email              VARCHAR(190)    NOT NULL,
  phone              VARCHAR(20)     NULL,
  password_hash      VARCHAR(255)    NOT NULL,                 -- password_hash() / PASSWORD_DEFAULT
  role               ENUM('user','support','admin','superadmin') NOT NULL DEFAULT 'user',
  status             ENUM('pending','active','suspended','banned') NOT NULL DEFAULT 'pending',
  email_verified_at  DATETIME        NULL,
  wallet_balance     BIGINT          NOT NULL DEFAULT 0,       -- kobo; source of truth = wallet_transactions
  package_prefix     VARCHAR(60)     NOT NULL DEFAULT 'com.orbit', -- default prefix for new apps
  avatar_path        VARCHAR(255)    NULL,
  country            CHAR(2)         NOT NULL DEFAULT 'NG',
  referral_code      VARCHAR(20)     NULL,
  referred_by        BIGINT UNSIGNED NULL,
  two_factor_secret  VARBINARY(255)  NULL,                     -- encrypted TOTP secret
  last_login_at      DATETIME        NULL,
  last_login_ip      VARCHAR(45)     NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  deleted_at         DATETIME        NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_uuid (uuid),
  UNIQUE KEY uq_users_email (email),
  UNIQUE KEY uq_users_referral (referral_code),
  KEY idx_users_status (status),
  KEY idx_users_role (role),
  CONSTRAINT fk_users_referred_by FOREIGN KEY (referred_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE user_tokens (                                     -- email verify, password reset, remember-me
  id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id      BIGINT UNSIGNED NOT NULL,
  type         ENUM('email_verify','password_reset','remember_me') NOT NULL,
  token_hash   CHAR(64)        NOT NULL,                       -- sha256 of token; raw token only in email/cookie
  expires_at   DATETIME        NOT NULL,
  used_at      DATETIME        NULL,
  ip_address   VARCHAR(45)     NULL,
  created_at   DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_tokens_hash (token_hash),
  KEY idx_tokens_user_type (user_id, type),
  CONSTRAINT fk_tokens_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE login_attempts (                                  -- brute-force protection
  id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  email        VARCHAR(190)    NULL,
  ip_address   VARCHAR(45)     NOT NULL,
  success      TINYINT(1)      NOT NULL DEFAULT 0,
  created_at   DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_login_ip_time (ip_address, created_at),
  KEY idx_login_email_time (email, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 2. PLANS, COUPONS, SUBSCRIPTIONS
-- ---------------------------------------------------------------------

CREATE TABLE plans (
  id                  INT UNSIGNED    NOT NULL AUTO_INCREMENT,
  slug                VARCHAR(50)     NOT NULL,                -- 'free-trial', 'yearly', 'lifetime', 'ios-addon'
  name                VARCHAR(100)    NOT NULL,
  description         TEXT            NULL,
  type                ENUM('trial','yearly','lifetime','addon') NOT NULL,
  platform            ENUM('android','ios','both')  NOT NULL DEFAULT 'android',
  price               BIGINT          NOT NULL DEFAULT 0,      -- kobo
  currency            CHAR(3)         NOT NULL DEFAULT 'NGN',
  duration_days       INT UNSIGNED    NULL,                    -- 365 for yearly, NULL for lifetime
  max_apps            INT UNSIGNED    NULL,                    -- NULL = unlimited
  max_builds_month    INT UNSIGNED    NULL,                    -- NULL = unlimited
  max_total_builds    INT UNSIGNED    NULL,                    -- e.g. 1 for free trial
  watermark           TINYINT(1)      NOT NULL DEFAULT 0,      -- trial builds show "Made with Orbit"
  allow_aab           TINYINT(1)      NOT NULL DEFAULT 1,      -- Play Store bundle
  allow_push          TINYINT(1)      NOT NULL DEFAULT 1,
  allow_admob         TINYINT(1)      NOT NULL DEFAULT 1,
  allow_remove_branding TINYINT(1)    NOT NULL DEFAULT 1,
  requires_plan_id    INT UNSIGNED    NULL,                    -- iOS add-on requires a base plan
  is_active           TINYINT(1)      NOT NULL DEFAULT 1,
  is_featured         TINYINT(1)      NOT NULL DEFAULT 0,
  sort_order          INT             NOT NULL DEFAULT 0,
  created_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_plans_slug (slug),
  KEY idx_plans_active (is_active, sort_order),
  CONSTRAINT fk_plans_requires FOREIGN KEY (requires_plan_id) REFERENCES plans(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE coupons (
  id                 INT UNSIGNED    NOT NULL AUTO_INCREMENT,
  code               VARCHAR(40)     NOT NULL,                 -- store UPPERCASE
  description        VARCHAR(255)    NULL,
  discount_type      ENUM('percent','fixed') NOT NULL,
  discount_value     BIGINT          NOT NULL,                 -- percent (1-100) or kobo
  max_discount       BIGINT          NULL,                     -- cap for percent coupons (kobo)
  min_amount         BIGINT          NOT NULL DEFAULT 0,       -- kobo
  plan_id            INT UNSIGNED    NULL,                     -- NULL = any plan
  max_uses           INT UNSIGNED    NULL,                     -- NULL = unlimited
  max_uses_per_user  INT UNSIGNED    NOT NULL DEFAULT 1,
  used_count         INT UNSIGNED    NOT NULL DEFAULT 0,
  starts_at          DATETIME        NULL,
  expires_at         DATETIME        NULL,
  is_active          TINYINT(1)      NOT NULL DEFAULT 1,
  created_by         BIGINT UNSIGNED NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_coupons_code (code),
  KEY idx_coupons_active (is_active, expires_at),
  CONSTRAINT fk_coupons_plan    FOREIGN KEY (plan_id)    REFERENCES plans(id) ON DELETE SET NULL,
  CONSTRAINT fk_coupons_creator FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE subscriptions (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id            BIGINT UNSIGNED NOT NULL,
  plan_id            INT UNSIGNED    NOT NULL,
  status             ENUM('pending','active','expired','cancelled','refunded') NOT NULL DEFAULT 'pending',
  starts_at          DATETIME        NULL,
  ends_at            DATETIME        NULL,                     -- NULL for lifetime
  builds_used        INT UNSIGNED    NOT NULL DEFAULT 0,       -- for max_total_builds limits
  auto_renew         TINYINT(1)      NOT NULL DEFAULT 0,
  renewal_reminder_sent_at DATETIME  NULL,
  cancelled_at       DATETIME        NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_subs_user_status (user_id, status),
  KEY idx_subs_ends (status, ends_at),                         -- cron: expire subscriptions
  CONSTRAINT fk_subs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_subs_plan FOREIGN KEY (plan_id) REFERENCES plans(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 3. PAYMENTS, WALLET, INVOICES
-- ---------------------------------------------------------------------

CREATE TABLE payments (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id            BIGINT UNSIGNED NOT NULL,
  reference          VARCHAR(64)     NOT NULL,                 -- our ref, e.g. ORB-20261126-XXXXXX
  gateway            ENUM('paystack','flutterwave','wallet','manual') NOT NULL,
  gateway_reference  VARCHAR(128)    NULL,                     -- Paystack/Flutterwave transaction ID
  purpose            ENUM('subscription','wallet_topup','addon') NOT NULL,
  plan_id            INT UNSIGNED    NULL,
  subscription_id    BIGINT UNSIGNED NULL,
  coupon_id          INT UNSIGNED    NULL,
  amount             BIGINT          NOT NULL,                 -- kobo, before discount
  discount           BIGINT          NOT NULL DEFAULT 0,       -- kobo
  amount_paid        BIGINT          NOT NULL,                 -- kobo, what gateway must confirm
  fee                BIGINT          NOT NULL DEFAULT 0,       -- gateway fee (kobo)
  currency           CHAR(3)         NOT NULL DEFAULT 'NGN',
  status             ENUM('pending','success','failed','abandoned','refunded') NOT NULL DEFAULT 'pending',
  channel            VARCHAR(30)     NULL,                     -- card, bank_transfer, ussd...
  verified_at        DATETIME        NULL,                     -- set ONLY after server-side verify call
  gateway_response   JSON            NULL,                     -- raw verify response for audit
  ip_address         VARCHAR(45)     NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_payments_reference (reference),
  UNIQUE KEY uq_payments_gateway_ref (gateway, gateway_reference), -- blocks double-crediting
  KEY idx_payments_user (user_id, created_at),
  KEY idx_payments_status (status, created_at),
  CONSTRAINT fk_payments_user   FOREIGN KEY (user_id)         REFERENCES users(id)         ON DELETE RESTRICT,
  CONSTRAINT fk_payments_plan   FOREIGN KEY (plan_id)         REFERENCES plans(id)         ON DELETE SET NULL,
  CONSTRAINT fk_payments_sub    FOREIGN KEY (subscription_id) REFERENCES subscriptions(id) ON DELETE SET NULL,
  CONSTRAINT fk_payments_coupon FOREIGN KEY (coupon_id)       REFERENCES coupons(id)       ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE webhook_events (                                  -- every incoming Paystack/Flutterwave webhook
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  gateway            ENUM('paystack','flutterwave') NOT NULL,
  event_id           VARCHAR(128)    NOT NULL,                 -- gateway event/transaction id (idempotency)
  event_type         VARCHAR(80)     NOT NULL,                 -- charge.success, etc.
  signature_valid    TINYINT(1)      NOT NULL DEFAULT 0,       -- HMAC / verif-hash check result
  payload            JSON            NOT NULL,
  payment_id         BIGINT UNSIGNED NULL,
  processed_at       DATETIME        NULL,
  error              VARCHAR(255)    NULL,
  ip_address         VARCHAR(45)     NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_webhook_event (gateway, event_id, event_type),
  KEY idx_webhook_unprocessed (processed_at),
  CONSTRAINT fk_webhook_payment FOREIGN KEY (payment_id) REFERENCES payments(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE wallet_transactions (                             -- ledger; never UPDATE, only INSERT
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id            BIGINT UNSIGNED NOT NULL,
  type               ENUM('credit','debit') NOT NULL,
  amount             BIGINT          NOT NULL,                 -- kobo, always positive
  balance_before     BIGINT          NOT NULL,
  balance_after      BIGINT          NOT NULL,
  source             ENUM('topup','purchase','refund','admin_adjust','referral_bonus') NOT NULL,
  payment_id         BIGINT UNSIGNED NULL,
  description        VARCHAR(255)    NULL,
  created_by         BIGINT UNSIGNED NULL,                     -- admin id if admin_adjust
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_wallet_user (user_id, created_at),
  CONSTRAINT fk_wallet_user    FOREIGN KEY (user_id)    REFERENCES users(id)    ON DELETE RESTRICT,
  CONSTRAINT fk_wallet_payment FOREIGN KEY (payment_id) REFERENCES payments(id) ON DELETE SET NULL,
  CONSTRAINT fk_wallet_admin   FOREIGN KEY (created_by) REFERENCES users(id)    ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE invoices (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  invoice_number     VARCHAR(30)     NOT NULL,                 -- INV-2026-000123
  user_id            BIGINT UNSIGNED NOT NULL,
  payment_id         BIGINT UNSIGNED NOT NULL,
  billing_name       VARCHAR(150)    NOT NULL,
  billing_email      VARCHAR(190)    NOT NULL,
  items              JSON            NOT NULL,                 -- [{desc, qty, unit_price, total}]
  subtotal           BIGINT          NOT NULL,
  discount           BIGINT          NOT NULL DEFAULT 0,
  tax                BIGINT          NOT NULL DEFAULT 0,       -- VAT if you enable it
  total              BIGINT          NOT NULL,
  currency           CHAR(3)         NOT NULL DEFAULT 'NGN',
  pdf_path           VARCHAR(255)    NULL,
  issued_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_invoice_number (invoice_number),
  UNIQUE KEY uq_invoice_payment (payment_id),
  KEY idx_invoice_user (user_id),
  CONSTRAINT fk_invoice_user    FOREIGN KEY (user_id)    REFERENCES users(id)    ON DELETE RESTRICT,
  CONSTRAINT fk_invoice_payment FOREIGN KEY (payment_id) REFERENCES payments(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE coupon_redemptions (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  coupon_id          INT UNSIGNED    NOT NULL,
  user_id            BIGINT UNSIGNED NOT NULL,
  payment_id         BIGINT UNSIGNED NOT NULL,
  discount_amount    BIGINT          NOT NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_redemption_payment (payment_id),
  KEY idx_redemption_coupon_user (coupon_id, user_id),
  CONSTRAINT fk_redeem_coupon  FOREIGN KEY (coupon_id)  REFERENCES coupons(id)  ON DELETE CASCADE,
  CONSTRAINT fk_redeem_user    FOREIGN KEY (user_id)    REFERENCES users(id)    ON DELETE CASCADE,
  CONSTRAINT fk_redeem_payment FOREIGN KEY (payment_id) REFERENCES payments(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 4. SIGNING KEYS
-- ---------------------------------------------------------------------

CREATE TABLE keystores (                                       -- one per user (reused across their apps)
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id            BIGINT UNSIGNED NOT NULL,
  label              VARCHAR(100)    NOT NULL DEFAULT 'Default',
  key_alias          VARCHAR(100)    NOT NULL,
  keystore_blob      MEDIUMBLOB      NOT NULL,                 -- ENCRYPTED .jks/.p12 bytes
  store_password_enc VARBINARY(255)  NOT NULL,                 -- ENCRYPTED
  key_password_enc   VARBINARY(255)  NOT NULL,                 -- ENCRYPTED
  cert_dn            VARCHAR(255)    NULL,                     -- CN=..., O=..., C=NG
  sha1_fingerprint   CHAR(59)        NULL,                     -- needed for Firebase / Google sign-in
  sha256_fingerprint CHAR(95)        NULL,                     -- needed for TWA assetlinks.json
  valid_until        DATE            NULL,
  is_default         TINYINT(1)      NOT NULL DEFAULT 1,
  backup_downloaded_at DATETIME      NULL,                     -- nag user until they back it up
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_keystore_user (user_id),
  CONSTRAINT fk_keystore_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE keystore_downloads (                              -- audit trail for backup downloads
  id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  keystore_id  BIGINT UNSIGNED NOT NULL,
  user_id      BIGINT UNSIGNED NOT NULL,
  ip_address   VARCHAR(45)     NULL,
  user_agent   VARCHAR(255)    NULL,
  created_at   DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_ksdl_keystore (keystore_id),
  CONSTRAINT fk_ksdl_keystore FOREIGN KEY (keystore_id) REFERENCES keystores(id) ON DELETE CASCADE,
  CONSTRAINT fk_ksdl_user     FOREIGN KEY (user_id)     REFERENCES users(id)     ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 5. APPS
-- ---------------------------------------------------------------------

CREATE TABLE apps (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  uuid               CHAR(36)        NOT NULL,
  user_id            BIGINT UNSIGNED NOT NULL,
  keystore_id        BIGINT UNSIGNED NULL,                     -- locked once first release build succeeds
  name               VARCHAR(50)     NOT NULL,                 -- shown under icon (keep short)
  short_name         VARCHAR(30)     NULL,
  website_url        VARCHAR(500)    NOT NULL,                 -- must be https://
  start_path         VARCHAR(255)    NOT NULL DEFAULT '/',
  allowed_domains    JSON            NULL,                     -- extra hosts that stay inside the app
  package_name       VARCHAR(150)    NOT NULL,                 -- com.orbit.appname (globally unique here)
  engine             ENUM('webview','twa') NOT NULL DEFAULT 'webview',
  platform           ENUM('android','ios','both') NOT NULL DEFAULT 'android',
  theme_color        CHAR(7)         NOT NULL DEFAULT '#0D6EFD',
  background_color   CHAR(7)         NOT NULL DEFAULT '#FFFFFF',
  status_bar_style   ENUM('light','dark') NOT NULL DEFAULT 'dark',
  orientation        ENUM('any','portrait','landscape') NOT NULL DEFAULT 'portrait',
  icon_path          VARCHAR(255)    NULL,                     -- 512x512 PNG, validated
  icon_sha256        CHAR(64)        NULL,
  splash_path        VARCHAR(255)    NULL,
  user_agent_suffix  VARCHAR(60)     NULL,                     -- e.g. "OrbitApp/1.0" so site can detect app
  current_version_id BIGINT UNSIGNED NULL,                     -- latest app_versions row
  url_last_checked_at DATETIME       NULL,
  url_check_status   ENUM('unchecked','ok','not_https','unreachable','blocked') NOT NULL DEFAULT 'unchecked',
  status             ENUM('draft','active','suspended','deleted') NOT NULL DEFAULT 'draft',
  suspended_reason   VARCHAR(255)    NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  deleted_at         DATETIME        NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_apps_uuid (uuid),
  UNIQUE KEY uq_apps_package (package_name),
  KEY idx_apps_user (user_id, status),
  KEY idx_apps_status (status),
  CONSTRAINT fk_apps_user     FOREIGN KEY (user_id)     REFERENCES users(id)     ON DELETE CASCADE,
  CONSTRAINT fk_apps_keystore FOREIGN KEY (keystore_id) REFERENCES keystores(id) ON DELETE RESTRICT
  -- fk_apps_current_version added at bottom (circular reference)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE app_features (                                    -- native feature toggles, 1 row per app
  app_id                  BIGINT UNSIGNED NOT NULL,
  push_enabled            TINYINT(1)  NOT NULL DEFAULT 0,
  pull_to_refresh         TINYINT(1)  NOT NULL DEFAULT 1,
  splash_enabled          TINYINT(1)  NOT NULL DEFAULT 1,
  splash_duration_ms      INT UNSIGNED NOT NULL DEFAULT 1500,
  offline_page_enabled    TINYINT(1)  NOT NULL DEFAULT 1,
  offline_message         VARCHAR(255) NOT NULL DEFAULT 'No internet connection. Please check your network and try again.',
  external_links_browser  TINYINT(1)  NOT NULL DEFAULT 1,
  deep_links_enabled      TINYINT(1)  NOT NULL DEFAULT 0,
  deep_link_hosts         JSON        NULL,                    -- ["example.com","www.example.com"]
  biometric_lock          TINYINT(1)  NOT NULL DEFAULT 0,
  file_upload             TINYINT(1)  NOT NULL DEFAULT 1,      -- <input type=file> support
  file_download           TINYINT(1)  NOT NULL DEFAULT 1,
  camera_permission       TINYINT(1)  NOT NULL DEFAULT 0,
  location_permission     TINYINT(1)  NOT NULL DEFAULT 0,
  zoom_enabled            TINYINT(1)  NOT NULL DEFAULT 0,
  keep_screen_on          TINYINT(1)  NOT NULL DEFAULT 0,
  exit_confirm            TINYINT(1)  NOT NULL DEFAULT 1,      -- "Press back again to exit"
  bottom_nav_enabled      TINYINT(1)  NOT NULL DEFAULT 0,      -- native tab bar (helps iOS 4.2 review)
  bottom_nav_items        JSON        NULL,                    -- [{label, icon, url}]
  admob_enabled           TINYINT(1)  NOT NULL DEFAULT 0,
  admob_app_id            VARCHAR(60) NULL,                    -- ca-app-pub-xxx~yyy
  admob_banner_id         VARCHAR(60) NULL,
  admob_interstitial_id   VARCHAR(60) NULL,
  admob_interstitial_every INT UNSIGNED NOT NULL DEFAULT 5,    -- page loads between interstitials
  custom_css              TEXT        NULL,                    -- injected CSS only (no JS — security rule)
  updated_at              DATETIME    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (app_id),
  CONSTRAINT fk_features_app FOREIGN KEY (app_id) REFERENCES apps(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE app_versions (                                    -- every release the user makes
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  app_id             BIGINT UNSIGNED NOT NULL,
  version_name       VARCHAR(20)     NOT NULL,                 -- "1.0.0" (user-facing)
  version_code       INT UNSIGNED    NOT NULL,                 -- 1,2,3... auto-incremented in PHP
  config_snapshot    JSON            NOT NULL,                 -- frozen copy of app + app_features at build time
  release_notes      TEXT            NULL,
  created_by         BIGINT UNSIGNED NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_version_code (app_id, version_code),
  KEY idx_versions_app (app_id, created_at),
  CONSTRAINT fk_versions_app     FOREIGN KEY (app_id)     REFERENCES apps(id)  ON DELETE CASCADE,
  CONSTRAINT fk_versions_creator FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 6. BUILD QUEUE
-- ---------------------------------------------------------------------

CREATE TABLE build_workers (                                   -- your VPS workers / cloud Mac connectors
  id                 INT UNSIGNED    NOT NULL AUTO_INCREMENT,
  name               VARCHAR(60)     NOT NULL,                 -- 'vps-lagos-1', 'codemagic'
  platform           ENUM('android','ios') NOT NULL,
  api_token_hash     CHAR(64)        NOT NULL,                 -- sha256 of worker's secret token
  max_concurrent     INT UNSIGNED    NOT NULL DEFAULT 2,
  is_active          TINYINT(1)      NOT NULL DEFAULT 1,
  last_heartbeat_at  DATETIME        NULL,
  ip_address         VARCHAR(45)     NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_worker_name (name),
  UNIQUE KEY uq_worker_token (api_token_hash)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE builds (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  uuid               CHAR(36)        NOT NULL,
  app_id             BIGINT UNSIGNED NOT NULL,
  app_version_id     BIGINT UNSIGNED NOT NULL,
  user_id            BIGINT UNSIGNED NOT NULL,
  subscription_id    BIGINT UNSIGNED NULL,                     -- which plan allowed this build
  platform           ENUM('android','ios') NOT NULL DEFAULT 'android',
  build_type         ENUM('release','debug') NOT NULL DEFAULT 'release',
  outputs            SET('apk','aab','ipa') NOT NULL DEFAULT 'apk,aab',
  watermark          TINYINT(1)      NOT NULL DEFAULT 0,
  status             ENUM('queued','building','done','failed','cancelled','expired') NOT NULL DEFAULT 'queued',
  priority           TINYINT UNSIGNED NOT NULL DEFAULT 5,      -- 1 = highest (paid), 9 = lowest (trial)
  attempts           TINYINT UNSIGNED NOT NULL DEFAULT 0,
  worker_id          INT UNSIGNED    NULL,
  locked_at          DATETIME        NULL,                     -- worker claims job: UPDATE ... WHERE locked_at IS NULL
  started_at         DATETIME        NULL,
  finished_at        DATETIME        NULL,
  duration_seconds   INT UNSIGNED    NULL,
  error_code         VARCHAR(50)     NULL,                     -- GRADLE_FAILED, ICON_INVALID, TIMEOUT...
  error_message      VARCHAR(500)    NULL,                     -- friendly message shown to user
  log                MEDIUMTEXT      NULL,                     -- full build log (admin + user view)
  external_build_id  VARCHAR(100)    NULL,                     -- Codemagic/Xcode Cloud build id (iOS)
  testflight_status  ENUM('none','uploading','processing','ready','failed') NOT NULL DEFAULT 'none',
  ip_address         VARCHAR(45)     NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_builds_uuid (uuid),
  KEY idx_builds_queue (status, platform, priority, created_at), -- worker picks next job
  KEY idx_builds_app (app_id, created_at),
  KEY idx_builds_user_time (user_id, created_at),              -- rate limiting
  CONSTRAINT fk_builds_app     FOREIGN KEY (app_id)         REFERENCES apps(id)          ON DELETE CASCADE,
  CONSTRAINT fk_builds_version FOREIGN KEY (app_version_id) REFERENCES app_versions(id)  ON DELETE CASCADE,
  CONSTRAINT fk_builds_user    FOREIGN KEY (user_id)        REFERENCES users(id)         ON DELETE CASCADE,
  CONSTRAINT fk_builds_sub     FOREIGN KEY (subscription_id) REFERENCES subscriptions(id) ON DELETE SET NULL,
  CONSTRAINT fk_builds_worker  FOREIGN KEY (worker_id)      REFERENCES build_workers(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE build_files (                                     -- outputs of a build
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  build_id           BIGINT UNSIGNED NOT NULL,
  file_type          ENUM('apk','aab','ipa','log','mapping') NOT NULL,
  storage_path       VARCHAR(500)    NOT NULL,                 -- outside web root; served via download.php
  file_size          BIGINT UNSIGNED NOT NULL,
  sha256             CHAR(64)        NOT NULL,
  download_count     INT UNSIGNED    NOT NULL DEFAULT 0,
  expires_at         DATETIME        NULL,                     -- cron deletes file after this
  deleted_at         DATETIME        NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_build_file (build_id, file_type),
  KEY idx_build_files_expiry (deleted_at, expires_at),
  CONSTRAINT fk_build_files_build FOREIGN KEY (build_id) REFERENCES builds(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 7. PUSH NOTIFICATIONS (Firebase)
-- ---------------------------------------------------------------------

CREATE TABLE push_settings (                                   -- 1 row per app
  app_id                 BIGINT UNSIGNED NOT NULL,
  firebase_project_id    VARCHAR(100)    NULL,
  google_services_json   MEDIUMBLOB      NULL,                 -- ENCRYPTED google-services.json (Android)
  google_service_plist   MEDIUMBLOB      NULL,                 -- ENCRYPTED GoogleService-Info.plist (iOS)
  service_account_json   MEDIUMBLOB      NULL,                 -- ENCRYPTED, for FCM HTTP v1 sending
  default_topic          VARCHAR(60)     NOT NULL DEFAULT 'all',
  notification_icon_path VARCHAR(255)    NULL,                 -- white/transparent small icon
  is_configured          TINYINT(1)      NOT NULL DEFAULT 0,
  updated_at             DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (app_id),
  CONSTRAINT fk_push_app FOREIGN KEY (app_id) REFERENCES apps(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE push_devices (                                    -- tokens registered by installed apps
  id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  app_id        BIGINT UNSIGNED NOT NULL,
  fcm_token     VARCHAR(255)    NOT NULL,
  platform      ENUM('android','ios') NOT NULL,
  app_version   VARCHAR(20)     NULL,
  is_active     TINYINT(1)      NOT NULL DEFAULT 1,
  last_seen_at  DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  created_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_push_device (app_id, fcm_token),
  KEY idx_push_devices_active (app_id, is_active),
  CONSTRAINT fk_push_devices_app FOREIGN KEY (app_id) REFERENCES apps(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE push_messages (                                   -- notifications the customer sends
  id             BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  app_id         BIGINT UNSIGNED NOT NULL,
  title          VARCHAR(100)    NOT NULL,
  body           VARCHAR(500)    NOT NULL,
  image_url      VARCHAR(500)    NULL,
  open_url       VARCHAR(500)    NULL,
  target         ENUM('all','topic','android','ios') NOT NULL DEFAULT 'all',
  topic          VARCHAR(60)     NULL,
  status         ENUM('draft','scheduled','sending','sent','failed') NOT NULL DEFAULT 'draft',
  scheduled_at   DATETIME        NULL,
  sent_at        DATETIME        NULL,
  success_count  INT UNSIGNED    NOT NULL DEFAULT 0,
  failure_count  INT UNSIGNED    NOT NULL DEFAULT 0,
  created_by     BIGINT UNSIGNED NULL,
  created_at     DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_push_msg_app (app_id, created_at),
  KEY idx_push_msg_schedule (status, scheduled_at),
  CONSTRAINT fk_push_msg_app  FOREIGN KEY (app_id)     REFERENCES apps(id)  ON DELETE CASCADE,
  CONSTRAINT fk_push_msg_user FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 8. iOS — PHASE 2 (customer's own Apple Developer account)
-- ---------------------------------------------------------------------

CREATE TABLE ios_credentials (
  id                   BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id              BIGINT UNSIGNED NOT NULL,
  apple_team_id        VARCHAR(20)     NOT NULL,
  team_name            VARCHAR(120)    NULL,
  asc_issuer_id        VARCHAR(64)     NOT NULL,               -- App Store Connect API issuer id
  asc_key_id           VARCHAR(20)     NOT NULL,
  asc_private_key_enc  BLOB            NOT NULL,               -- ENCRYPTED .p8 contents
  dist_cert_p12_enc    MEDIUMBLOB      NULL,                   -- ENCRYPTED (if not auto-managed)
  dist_cert_password_enc VARBINARY(255) NULL,
  dist_cert_expires_at DATE            NULL,
  status               ENUM('unverified','verified','invalid','expired') NOT NULL DEFAULT 'unverified',
  last_verified_at     DATETIME        NULL,
  created_at           DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at           DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_ios_user_team (user_id, apple_team_id),
  CONSTRAINT fk_ios_cred_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE ios_app_settings (                                -- 1 row per app with iOS enabled
  app_id                 BIGINT UNSIGNED NOT NULL,
  ios_credential_id      BIGINT UNSIGNED NOT NULL,
  bundle_id              VARCHAR(150)    NOT NULL,             -- usually same as package_name
  asc_app_id             VARCHAR(20)     NULL,                 -- App Store Connect app id
  provisioning_profile_enc MEDIUMBLOB    NULL,                 -- ENCRYPTED
  build_number           INT UNSIGNED    NOT NULL DEFAULT 0,   -- CFBundleVersion, auto-incremented
  updated_at             DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (app_id),
  UNIQUE KEY uq_ios_bundle (bundle_id),
  CONSTRAINT fk_ios_app_app  FOREIGN KEY (app_id)            REFERENCES apps(id)            ON DELETE CASCADE,
  CONSTRAINT fk_ios_app_cred FOREIGN KEY (ios_credential_id) REFERENCES ios_credentials(id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 9. FREE PWA OPTION
-- ---------------------------------------------------------------------

CREATE TABLE pwa_packages (
  id                 BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id            BIGINT UNSIGNED NULL,                     -- NULL = guest generated
  app_id             BIGINT UNSIGNED NULL,                     -- if made from an existing app
  website_url        VARCHAR(500)    NOT NULL,
  name               VARCHAR(50)     NOT NULL,
  short_name         VARCHAR(30)     NOT NULL,
  theme_color        CHAR(7)         NOT NULL,
  background_color   CHAR(7)         NOT NULL,
  display_mode       ENUM('standalone','fullscreen','minimal-ui','browser') NOT NULL DEFAULT 'standalone',
  icon_path          VARCHAR(255)    NULL,
  manifest_json      JSON            NOT NULL,
  service_worker_js  MEDIUMTEXT      NOT NULL,                 -- generated from OUR template only
  zip_path           VARCHAR(255)    NULL,                     -- manifest + sw + icons bundle
  download_count     INT UNSIGNED    NOT NULL DEFAULT 0,
  ip_address         VARCHAR(45)     NULL,
  created_at         DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_pwa_user (user_id),
  KEY idx_pwa_ip_time (ip_address, created_at),                -- rate limit guests
  CONSTRAINT fk_pwa_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL,
  CONSTRAINT fk_pwa_app  FOREIGN KEY (app_id)  REFERENCES apps(id)  ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- 10. ADMIN, SETTINGS, EMAIL, NOTIFICATIONS
-- ---------------------------------------------------------------------

CREATE TABLE admin_actions (                                   -- audit log of everything admins do
  id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  admin_id      BIGINT UNSIGNED NULL,
  action        VARCHAR(80)     NOT NULL,                      -- 'user.suspend', 'plan.update', 'build.retry'
  target_type   VARCHAR(40)     NULL,                          -- 'user','app','build','plan','coupon','setting'
  target_id     BIGINT UNSIGNED NULL,
  old_values    JSON            NULL,
  new_values    JSON            NULL,
  note          VARCHAR(255)    NULL,
  ip_address    VARCHAR(45)     NULL,
  created_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_admin_actions_admin (admin_id, created_at),
  KEY idx_admin_actions_target (target_type, target_id),
  CONSTRAINT fk_admin_actions_admin FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE settings (                                        -- key/value site settings
  `key`         VARCHAR(80)     NOT NULL,
  `value`       TEXT            NULL,
  `type`        ENUM('string','int','bool','json','color','image','secret') NOT NULL DEFAULT 'string',
  `group`       VARCHAR(40)     NOT NULL DEFAULT 'general',    -- general, branding, payments, build, email
  is_public     TINYINT(1)      NOT NULL DEFAULT 0,            -- safe to expose to frontend
  updated_by    BIGINT UNSIGNED NULL,
  updated_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`key`),
  KEY idx_settings_group (`group`),
  CONSTRAINT fk_settings_user FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE feature_flags (                                   -- platform-wide on/off switches (admin)
  `key`         VARCHAR(60)     NOT NULL,                      -- 'ios_builds', 'twa_engine', 'admob', 'signup'
  enabled       TINYINT(1)      NOT NULL DEFAULT 1,
  description   VARCHAR(255)    NULL,
  updated_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE email_templates (
  id            INT UNSIGNED    NOT NULL AUTO_INCREMENT,
  slug          VARCHAR(60)     NOT NULL,                      -- 'welcome','verify_email','build_done'...
  name          VARCHAR(100)    NOT NULL,
  subject       VARCHAR(200)    NOT NULL,
  body_html     MEDIUMTEXT      NOT NULL,                      -- uses {{placeholders}}
  placeholders  JSON            NULL,                          -- documented vars for admin UI
  is_active     TINYINT(1)      NOT NULL DEFAULT 1,
  updated_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_email_tpl_slug (slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE email_queue (
  id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id       BIGINT UNSIGNED NULL,
  to_email      VARCHAR(190)    NOT NULL,
  template_slug VARCHAR(60)     NULL,
  subject       VARCHAR(200)    NOT NULL,
  body_html     MEDIUMTEXT      NOT NULL,
  status        ENUM('pending','sent','failed') NOT NULL DEFAULT 'pending',
  attempts      TINYINT UNSIGNED NOT NULL DEFAULT 0,
  error         VARCHAR(255)    NULL,
  sent_at       DATETIME        NULL,
  created_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_email_queue_status (status, created_at),
  CONSTRAINT fk_email_queue_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE notifications (                                   -- in-dashboard bell notifications
  id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id       BIGINT UNSIGNED NOT NULL,
  type          VARCHAR(40)     NOT NULL,                      -- build_done, build_failed, payment_success...
  title         VARCHAR(150)    NOT NULL,
  message       VARCHAR(500)    NOT NULL,
  link          VARCHAR(255)    NULL,
  read_at       DATETIME        NULL,
  created_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_notif_user_unread (user_id, read_at),
  CONSTRAINT fk_notif_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE rate_limits (                                     -- generic limiter (builds, URL checks, PWA)
  id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  bucket        VARCHAR(120)    NOT NULL,                      -- 'build:user:42', 'urlcheck:ip:1.2.3.4'
  hits          INT UNSIGNED    NOT NULL DEFAULT 1,
  window_start  DATETIME        NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_rate_bucket (bucket, window_start)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE upload_scans (                                    -- icon/splash validation + scan results
  id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  user_id       BIGINT UNSIGNED NULL,                           -- NULL = guest (free PWA tool)
  app_id        BIGINT UNSIGNED NULL,
  purpose       ENUM('icon','splash','notification_icon','pwa_icon') NOT NULL,
  original_name VARCHAR(255)    NOT NULL,
  stored_path   VARCHAR(255)    NULL,
  mime_type     VARCHAR(50)     NOT NULL,
  width         INT UNSIGNED    NULL,
  height        INT UNSIGNED    NULL,
  file_size     INT UNSIGNED    NOT NULL,
  sha256        CHAR(64)        NOT NULL,
  result        ENUM('accepted','rejected') NOT NULL,
  reject_reason VARCHAR(255)    NULL,                          -- 'not square', 'over 1MB', 'clamav: infected'
  created_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_scans_user (user_id, created_at),
  CONSTRAINT fk_scans_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL,
  CONSTRAINT fk_scans_app  FOREIGN KEY (app_id)  REFERENCES apps(id)  ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- Circular FK: apps.current_version_id -> app_versions.id
-- ---------------------------------------------------------------------
ALTER TABLE apps
  ADD CONSTRAINT fk_apps_current_version
  FOREIGN KEY (current_version_id) REFERENCES app_versions(id) ON DELETE SET NULL;

SET FOREIGN_KEY_CHECKS = 1;

-- =====================================================================
--  SEED DATA (edit prices in admin panel later)
-- =====================================================================

INSERT INTO plans (slug, name, description, type, platform, price, duration_days, max_apps, max_builds_month, max_total_builds, watermark, allow_aab, allow_push, allow_admob, allow_remove_branding, is_featured, sort_order) VALUES
('free-trial', 'Free Trial', 'Try it: 1 Android build with watermark splash.', 'trial',    'android', 0,        7,    1,    NULL, 1,    1, 0, 0, 0, 0, 0, 1),
('yearly',     'Yearly',     'Unlimited Android rebuilds for 1 year, APK + AAB.', 'yearly', 'android', 2500000,  365,  3,    30,   NULL, 0, 1, 1, 1, 1, 1, 2),
('lifetime',   'Lifetime',   'Pay once. Android builds forever, APK + AAB.',  'lifetime', 'android', 7500000,  NULL, 10,   50,   NULL, 0, 1, 1, 1, 1, 0, 3);

INSERT INTO plans (slug, name, description, type, platform, price, duration_days, max_apps, max_builds_month, requires_plan_id, sort_order)
SELECT 'ios-addon', 'iOS Add-on', 'Build iOS apps and upload to TestFlight (needs your own Apple Developer account).',
       'addon', 'ios', 4000000, 365, 3, 10, id, 4
FROM plans WHERE slug = 'yearly';

INSERT INTO settings (`key`, `value`, `type`, `group`, is_public) VALUES
('site_name',              'Orbit App Builder',        'string', 'branding', 1),
('site_logo',              '/assets/img/logo.png',     'image',  'branding', 1),
('primary_color',          '#0D6EFD',                  'color',  'branding', 1),
('support_email',          'support@orbitearn.org',    'string', 'general',  1),
('default_package_prefix', 'com.orbit',                'string', 'build',    0),
('build_file_retention_days', '30',                    'int',    'build',    0),
('max_builds_per_hour',    '3',                        'int',    'build',    0),
('max_icon_size_kb',       '1024',                     'int',    'build',    0),
('build_timeout_minutes',  '20',                       'int',    'build',    0),
('paystack_public_key',    '',                         'string', 'payments', 0),
('paystack_secret_key',    '',                         'secret', 'payments', 0),
('flutterwave_public_key', '',                         'string', 'payments', 0),
('flutterwave_secret_key', '',                         'secret', 'payments', 0),
('flutterwave_secret_hash','',                         'secret', 'payments', 0),
('default_gateway',        'paystack',                 'string', 'payments', 0),
('smtp_host',              '',                         'string', 'email',    0),
('smtp_port',              '587',                      'int',    'email',    0),
('smtp_user',              '',                         'string', 'email',    0),
('smtp_pass',              '',                         'secret', 'email',    0),
('smtp_from_name',         'Orbit App Builder',        'string', 'email',    0),
('smtp_from_email',        '',                         'string', 'email',    0);

INSERT INTO feature_flags (`key`, enabled, description) VALUES
('signup',        1, 'Allow new registrations'),
('android_builds',1, 'Accept Android build jobs'),
('twa_engine',    1, 'Offer Trusted Web Activity engine'),
('ios_builds',    0, 'Phase 2 — turn on when cloud Mac is ready'),
('pwa_generator', 1, 'Free PWA option'),
('admob',         1, 'Allow AdMob toggle in apps'),
('wallet',        1, 'Allow wallet top-up and wallet payments');

INSERT INTO email_templates (slug, name, subject, body_html, placeholders) VALUES
('welcome',        'Welcome',              'Welcome to {{site_name}}',            '<p>Hi {{name}},</p><p>Your account is ready. Create your first app now.</p>', '["name","site_name"]'),
('verify_email',   'Verify email',         'Verify your email',                   '<p>Hi {{name}},</p><p><a href="{{link}}">Click here to verify</a>. Link expires in 24 hours.</p>', '["name","link"]'),
('password_reset', 'Password reset',       'Reset your password',                 '<p>Hi {{name}},</p><p><a href="{{link}}">Reset password</a>. Ignore if you did not request this.</p>', '["name","link"]'),
('build_done',     'Build finished',       'Your app {{app_name}} is ready',      '<p>Hi {{name}},</p><p>Version {{version}} of {{app_name}} built successfully. <a href="{{link}}">Download</a></p>', '["name","app_name","version","link"]'),
('build_failed',   'Build failed',         'Build failed for {{app_name}}',       '<p>Hi {{name}},</p><p>The build failed: {{error}}. <a href="{{link}}">View log</a></p>', '["name","app_name","error","link"]'),
('payment_success','Payment received',     'Payment received — {{amount}}',       '<p>Hi {{name}},</p><p>We received {{amount}} for {{plan}}. Invoice: {{invoice_number}}</p>', '["name","amount","plan","invoice_number"]'),
('sub_expiring',   'Subscription expiring','Your plan expires on {{date}}',       '<p>Hi {{name}},</p><p>Your {{plan}} plan expires on {{date}}. Renew to keep updating your apps.</p>', '["name","plan","date"]'),
('keystore_backup','Back up your key',     'Important: back up your signing key', '<p>Hi {{name}},</p><p>Download your keystore backup. Without it you cannot update your app on Google Play.</p>', '["name"]');
