-- ============================================================
-- FireWin777 - FRESH INSTALL database (single file).
-- UPDATE 2026-11-18 (FireWin777 parity): this file is the FireWin v2
-- schema PLUS the FireWin-parity additions at the end of the file
-- (instant-game score tables, direct-API store tables,
-- payment_methods.bonus_percent + wider icon, orders
-- .method_bonus_percent, and the missing settings seeds).
-- FRESH installs only. Existing FireWin databases must use
-- migrate-2026-11-18.sql instead -- never import this file over
-- a database that already has users, or the INSERT ... ON
-- DUPLICATE KEY rows below will overwrite live settings.

-- Import this ONE file in phpMyAdmin (in order, top to bottom).
-- Base schema + every patch the code references, merged.
-- No admin user is seeded: sign up, then make the first admin
-- with SQL (see the deployment checklist), then log in.
-- No payment checkout links or QR codes are seeded: the admin
-- fills those in Admin -> Payments after install.
-- ============================================================

-- =====================================================================
-- FireWin777 Database v2 - FRESH schema (PHP + MySQL, for cPanel)
-- Import in cPanel > phpMyAdmin > select your database > Import.
-- WARNING: v2 is a FRESH schema. If you imported the old (v1) file, first
-- DROP all existing tables in phpMyAdmin, then import this file.
-- See README-SETUP.txt Step 2. Back up first if the database has real users.
-- Covers: Customers, Accounts, Chat, Games, Wallet, Orders, Withdrawals,
-- Bonus-to-Main Transfers, Withdraw Accounts, KYC, Support, Referrals.
-- Demo - no cash value, no real-money deposits. $ / Coins are display only.
-- =====================================================================
SET NAMES utf8mb4;
SET time_zone = '+00:00';

-- ---------- Admins ----------
CREATE TABLE IF NOT EXISTS admins (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(80) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_login_at DATETIME DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Customers / Accounts ----------
CREATE TABLE IF NOT EXISTS users (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  first_name VARCHAR(60) DEFAULT NULL,
  last_name VARCHAR(60) DEFAULT NULL,
  username VARCHAR(30) DEFAULT NULL,
  email VARCHAR(190) NOT NULL UNIQUE,
  phone VARCHAR(40) DEFAULT NULL,
  password_hash VARCHAR(255) NOT NULL,
  balance DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_balance DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  status ENUM('active','blocked','banned','suspended') NOT NULL DEFAULT 'active',
  device_fingerprint VARCHAR(190) DEFAULT NULL,
  signup_ip VARCHAR(45) DEFAULT NULL,
  last_login_ip VARCHAR(45) DEFAULT NULL,
  last_login_at DATETIME DEFAULT NULL,
  last_active_at DATETIME DEFAULT NULL,
  city VARCHAR(120) DEFAULT NULL,
  country VARCHAR(120) DEFAULT NULL,
  address VARCHAR(255) DEFAULT NULL,
  referral_code VARCHAR(20) NOT NULL UNIQUE,
  referred_by INT UNSIGNED DEFAULT NULL,
  avatar_url VARCHAR(500) DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_users_username (username),
  INDEX idx_users_created (created_at),
  INDEX idx_users_device (device_fingerprint),
  INDEX idx_users_city (city),
  INDEX idx_users_country (country),
  CONSTRAINT fk_users_referrer FOREIGN KEY (referred_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS user_sessions (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  token_hash CHAR(64) NOT NULL UNIQUE,
  device VARCHAR(255) DEFAULT NULL,
  ip_address VARCHAR(45) DEFAULT NULL,
  expires_at DATETIME NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_sessions_user (user_id),
  CONSTRAINT fk_sessions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS login_logs (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED DEFAULT NULL,
  email_attempted VARCHAR(190) DEFAULT NULL,
  ip_address VARCHAR(45) DEFAULT NULL,
  device VARCHAR(255) DEFAULT NULL,
  success TINYINT(1) NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_login_created (created_at),
  INDEX idx_login_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Wallet ----------
-- type values used: signup, admin_add, admin_remove, order_credit (reserved -
-- orders do NOT auto-credit; admin adds manually), spin_cost, spin_prize,
-- withdraw_request, withdraw (admin deduction for an approved withdrawal),
-- transfer_out (Bonus Wallet, -amount), transfer_in (Main Wallet, +received),
-- transfer_fee (informational row: fee kept from the transfer),
-- referral_bonus.
-- balance_after / bonus_balance_after are snapshots AFTER the row's own
-- movement. For transfer_fee and withdraw_request rows the snapshots are
-- unchanged on purpose: the fee is part of the transfer_out amount, and a
-- withdraw request deducts nothing until the admin deducts it.
CREATE TABLE IF NOT EXISTS wallet_transactions (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  type VARCHAR(40) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  balance_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_balance_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  note VARCHAR(500) DEFAULT NULL,
  order_id BIGINT UNSIGNED DEFAULT NULL,
  withdrawal_id BIGINT UNSIGNED DEFAULT NULL,
  transfer_id BIGINT UNSIGNED DEFAULT NULL,
  created_by VARCHAR(20) NOT NULL DEFAULT 'system',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_tx_user (user_id),
  INDEX idx_tx_created (created_at),
  INDEX idx_tx_type (type),
  CONSTRAINT fk_tx_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Games ----------
CREATE TABLE IF NOT EXISTS games (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  slug VARCHAR(120) NOT NULL UNIQUE,
  name VARCHAR(160) NOT NULL,
  category VARCHAR(80) NOT NULL DEFAULT 'Popular',
  image_url VARCHAR(600) DEFAULT NULL,
  description TEXT DEFAULT NULL,
  is_featured TINYINT(1) NOT NULL DEFAULT 0,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  play_url VARCHAR(600) DEFAULT NULL,
  play_label VARCHAR(80) DEFAULT NULL,
  download_url VARCHAR(600) DEFAULT NULL,
  download_label VARCHAR(80) DEFAULT NULL,
  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
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS game_plays (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  game_id INT UNSIGNED NOT NULL,
  play_date DATE NOT NULL,
  played_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_plays_date (play_date),
  INDEX idx_plays_user_date (user_id, play_date),
  CONSTRAINT fk_plays_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_plays_game FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- NEW v2: per-user game on/off, set by admin. No row = enabled (default).
-- A row with enabled=0 hides that game for that user only.
CREATE TABLE IF NOT EXISTS user_game_access (
  user_id INT UNSIGNED NOT NULL,
  game_id INT UNSIGNED NOT NULL,
  enabled TINYINT(1) NOT NULL DEFAULT 1,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (user_id, game_id),
  CONSTRAINT fk_uga_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_uga_game FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Payment methods (Deposit + Withdraw) ----------
-- UPDATE 2026-11-18 (FireWin parity): bonus_percent is BACK. It is the
-- per-method deposit bonus % (e.g. Chime 15%, Cash App 10%), paid into
-- the MAIN wallet at approval from the admin coin pool. It stacks with
-- the sign-up bonus and any claimed offer. See FireWin orders.php and
-- helpers.php ws_maybe_method_bonus(). An approved order still credits
-- exactly amount_paid as well; the bonus is extra, on top.
-- icon is VARCHAR(600), not VARCHAR(40): FireWin's own manage.php
-- comment records that VARCHAR(40) cut any image URL / uploaded photo
-- to 40 chars and broke the method image. The front-end default icons
-- are short ('$', 'C', emoji), but an uploaded image URL must fit.
CREATE TABLE IF NOT EXISTS payment_methods (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  type VARCHAR(40) NOT NULL DEFAULT 'other',
  subtitle VARCHAR(200) DEFAULT NULL,
  icon VARCHAR(600) DEFAULT NULL,
  pill_text VARCHAR(80) DEFAULT NULL,
  qr_image_url VARCHAR(600) DEFAULT NULL,
  checkout_link VARCHAR(600) DEFAULT NULL,
  pay_label VARCHAR(80) NOT NULL DEFAULT 'Pay',
  min_amount DECIMAL(12,2) DEFAULT NULL,
  max_amount DECIMAL(12,2) DEFAULT NULL,
  instructions TEXT DEFAULT NULL,
  bonus_percent DECIMAL(6,2) NOT NULL DEFAULT 0,
  allow_withdraw TINYINT(1) NOT NULL DEFAULT 1,
  withdraw_subtitle VARCHAR(200) DEFAULT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  sort_order INT NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Buy Coins orders (NO bonus logic) ----------
CREATE TABLE IF NOT EXISTS orders (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  payment_method_id INT UNSIGNED DEFAULT NULL,
  method_name VARCHAR(120) DEFAULT NULL,
  method_bonus_percent DECIMAL(6,2) DEFAULT NULL,
  amount_paid DECIMAL(12,2) NOT NULL,
  email VARCHAR(190) NOT NULL,
  screenshot_url VARCHAR(600) DEFAULT NULL,
  status ENUM('pending','approved','awaiting_admin_add','credited','rejected') NOT NULL DEFAULT 'pending',
  admin_note VARCHAR(500) DEFAULT NULL,
  decided_at DATETIME DEFAULT NULL,
  decided_by INT UNSIGNED DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_orders_user (user_id),
  INDEX idx_orders_status (status),
  CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- NEW v2: Withdrawals ----------
-- Flow: user creates (status=pending, NOTHING is deducted) -> admin approves
-- (status=awaiting_deduction, still deducts nothing) -> admin deducts the
-- amount from the user's Main Wallet with Admin > Users > Adjust Balance,
-- which logs a 'withdraw' wallet transaction with withdrawal_id set.
-- Reject changes nothing in the wallet.
CREATE TABLE IF NOT EXISTS withdrawals (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  payment_method_id INT UNSIGNED DEFAULT NULL,
  method_name VARCHAR(120) DEFAULT NULL,
  amount DECIMAL(12,2) NOT NULL,
  email VARCHAR(190) DEFAULT NULL,
  receiving_details VARCHAR(255) DEFAULT NULL,
  note VARCHAR(500) DEFAULT NULL,
  status ENUM('pending','approved','awaiting_deduction','rejected') NOT NULL DEFAULT 'pending',
  admin_note VARCHAR(500) DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  decided_at DATETIME DEFAULT NULL,
  decided_by INT UNSIGNED DEFAULT NULL,
  INDEX idx_wd_user (user_id),
  INDEX idx_wd_status (status),
  CONSTRAINT fk_wd_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- NEW v2: saved Withdraw Accounts (one row per user per method) ----------
CREATE TABLE IF NOT EXISTS withdraw_accounts (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  payment_method_id INT UNSIGNED DEFAULT NULL,
  method_name VARCHAR(120) DEFAULT NULL,
  details VARCHAR(255) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_withdraw_account (user_id, payment_method_id),
  CONSTRAINT fk_wa_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- NEW v2: Bonus Wallet -> Main Wallet transfers ----------
-- amount leaves the Bonus Wallet in full. fee (default 0.10, from settings)
-- is kept by the house. received = amount - fee lands in the Main Wallet.
CREATE TABLE IF NOT EXISTS bonus_transfers (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  fee DECIMAL(12,2) NOT NULL DEFAULT 0.10,
  received DECIMAL(12,2) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_bt_user (user_id),
  CONSTRAINT fk_bt_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Spin & Win ----------
CREATE TABLE IF NOT EXISTS spin_history (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  spin_type ENUM('free','paid') NOT NULL DEFAULT 'free',
  cost DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  multiplier DECIMAL(5,2) NOT NULL DEFAULT 0.00,
  prize DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  spin_date DATE NOT NULL,
  spun_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_spin_user_date (user_id, spin_date),
  CONSTRAINT fk_spin_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Live Support / Chat ----------
-- v2: status open/resolved (+closed kept for old habits), an assignee admin,
-- and labels (comma-separated text, e.g. "vip,withdraw").
CREATE TABLE IF NOT EXISTS support_conversations (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED DEFAULT NULL,
  guest_name VARCHAR(120) DEFAULT NULL,
  guest_email VARCHAR(190) DEFAULT NULL,
  status ENUM('open','resolved','closed') NOT NULL DEFAULT 'open',
  assignee_admin_id INT UNSIGNED DEFAULT NULL,
  labels VARCHAR(255) DEFAULT NULL,
  last_message_at DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_conv_user (user_id),
  INDEX idx_conv_status (status),
  INDEX idx_conv_assignee (assignee_admin_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- sender_type: 'user' (customer), 'admin' (support reply), 'guest'.
-- is_private_note=1 rows are ADMIN-ONLY internal notes: the user API never
-- returns them. A private note always has sender_type='admin'.
-- There are NO automatic replies anywhere in this backend: a customer only
-- ever receives messages a human admin typed.
CREATE TABLE IF NOT EXISTS support_messages (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  conversation_id BIGINT UNSIGNED NOT NULL,
  sender_type ENUM('user','admin','guest') NOT NULL DEFAULT 'user',
  sender_id INT UNSIGNED DEFAULT NULL,
  message TEXT DEFAULT NULL,
  attachment_url VARCHAR(600) DEFAULT NULL,
  attachment_type VARCHAR(80) DEFAULT NULL,
  is_private_note TINYINT(1) NOT NULL DEFAULT 0,
  is_read TINYINT(1) NOT NULL DEFAULT 0,
  status ENUM('sent','delivered','read') NOT NULL DEFAULT 'sent',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_msg_conv (conversation_id),
  CONSTRAINT fk_msg_conv FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- KYC / Verification ----------
-- v2: reject_reason is shown to the user when a document is rejected.
CREATE TABLE IF NOT EXISTS kyc_documents (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  doc_type VARCHAR(80) NOT NULL DEFAULT 'id',
  file_url VARCHAR(600) NOT NULL,
  file_url_2 VARCHAR(600) DEFAULT NULL,
  status ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  admin_note VARCHAR(500) DEFAULT NULL,
  reject_reason TEXT DEFAULT NULL,
  reviewed_by INT UNSIGNED DEFAULT NULL,
  submitted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  reviewed_at DATETIME DEFAULT NULL,
  INDEX idx_kyc_user (user_id),
  INDEX idx_kyc_status (status),
  CONSTRAINT fk_kyc_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Notifications / Referrals / Settings ----------
CREATE TABLE IF NOT EXISTS notifications (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED DEFAULT NULL,
  title VARCHAR(200) NOT NULL,
  body TEXT DEFAULT NULL,
  type VARCHAR(40) NOT NULL DEFAULT 'info',
  is_read TINYINT(1) NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_notif_user (user_id),
  CONSTRAINT fk_notif_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS referrals (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  referrer_id INT UNSIGNED NOT NULL,
  referred_user_id INT UNSIGNED NOT NULL UNIQUE,
  bonus_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  status ENUM('pending','paid') NOT NULL DEFAULT 'pending',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_ref_referrer FOREIGN KEY (referrer_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_ref_referred FOREIGN KEY (referred_user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS site_settings (
  setting_key VARCHAR(120) PRIMARY KEY,
  setting_value TEXT DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Buyer maintenance-fee submissions ----------
-- One row per maintenance-fee payment the buyer (site admin)
-- submits from the admin panel. The row is created as pending,
-- pushed to GMPanel (maintenance_receive.php), and the panel's
-- id is stored back in panel_submission_id when the push
-- succeeds. The panel later pushes the approval back through
-- site_sync.php action=maintenance_set, which sets
-- maintenance_expires_at / maintenance_status below.
-- Dedupe is done in code (api/maintenance.php) on
-- (submitted_at, months, amount): a resubmit within 10 minutes
-- of an identical pending row returns the existing row instead
-- of creating a duplicate. panel_submission_id is a plain INDEX
-- (not UNIQUE) so multiple NULLs are allowed.
CREATE TABLE IF NOT EXISTS maintenance_submissions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  months TINYINT NOT NULL,
  amount DECIMAL(10,2) NOT NULL,
  binance_id VARCHAR(128) NOT NULL DEFAULT '',
  proof_path VARCHAR(255) NOT NULL DEFAULT '',
  status ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
  submitted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  decided_at DATETIME NULL DEFAULT NULL,
  decided_by VARCHAR(64) NULL DEFAULT NULL,
  panel_submission_id INT NULL DEFAULT NULL,
  INDEX idx_maintenance_status (status),
  INDEX idx_maintenance_panel (panel_submission_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Admin demo-coin pool log ----------
-- Every generation and every distribution of pool coins to customers.
CREATE TABLE IF NOT EXISTS coin_pool_log (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  admin_id INT UNSIGNED NULL,
  change_amount DECIMAL(12,2) NOT NULL,
  balance_after DECIMAL(12,2) NOT NULL,
  reason VARCHAR(255) NOT NULL DEFAULT '',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ---------- Default settings ----------
INSERT INTO site_settings (setting_key, setting_value) VALUES
('site_name','FireWin777'),
('support_email','supportfirewin777@gmail.com'),
('smtp_host', ''),
('smtp_port', ''),
('smtp_user', ''),
('smtp_pass', ''),
('font_family','system'),
('font_size','16'),
('demo_note', 'Demo — no cash value, no real-money deposits. Entertainment only. 18+ only.'),
('allowed_email_domains','gmail.com,hotmail.com,icloud.com,outlook.com'),
('one_account_per_device','1'),
('min_deposit','5'),('min_withdraw','20'),
('deposit_enabled','1'),('withdraw_enabled','1'),
('transfer_min','0.1'),('transfer_fee','0'),('bonus_transfer_enabled','1'),
('spin_free_per_day','1'),('spin_paid_cost','5'),
('spin_multipliers','0,0.2,0.5,0.8,1,1.2,1.5,1.8'),
('referral_bonus','10'),
('signup_bonus_enabled','1'),
('signup_bonus_percent','150'),
('withdraw_mult','4'),
('max_accounts_per_device','5'),
('checkin_json','{"days":[50,75,100,150,200,300,500]}'),
('bonuses_json','[]'),
('instant_games_json','[]'),
('support_welcome','Hi! How can we help you today?'),
('admin_coin_pool','100000'),
('google_client_id','')
ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value);

-- ---------- Maintenance-fee settings (buyer side) ----------
-- maintenance_expires_at NULL = active, no expiry set yet; the
-- panel sets it on the first approval (site_sync.php
-- action=maintenance_set). maintenance_status is 'active' until
-- then. No Binance ID, WhatsApp number or prices are seeded
-- here: those live in GMPanel and are pulled into
-- maintenance_config_json by api/maintenance.php?action=refresh_config.
-- Safe to re-run: an existing value is NEVER overwritten, so a
-- re-import cannot wipe an expiry the panel already set.
INSERT INTO site_settings (setting_key, setting_value) VALUES
('maintenance_expires_at', NULL),
('maintenance_status', 'active')
ON DUPLICATE KEY UPDATE setting_value=setting_value;

-- ---------- Payment methods (admin edits every text/link in Admin > Payments) ----------
INSERT INTO payment_methods (id,name,type,subtitle,pill_text,min_amount,max_amount,instructions,bonus_percent,allow_withdraw,sort_order) VALUES
(1,'Cash App','cashapp','Fast & easy','Popular',5,1000,'Pay on Cash App, then submit Amount paid + Email + Screenshot.',10,1,1),
(2,'Chime','chime','Fast & easy','Popular',5,1000,'Pay on Chime, then submit Amount paid + Email + Screenshot.',15,1,2),
(3,'Debit Card','card','Any amount','Card',NULL,NULL,'Pay by debit card, then submit Amount paid + Email + Screenshot.',0,0,3)
ON DUPLICATE KEY UPDATE name=VALUES(name);

-- ---------- 17 games (names as confirmed by owner) ----------
INSERT INTO games (slug,name,category,is_featured,sort_order,description) VALUES
('vegas-sweep','Vegas Sweep','Sweeps',0,1,'Vegas Sweep - a popular player favourite. Create an account to play.'),
('orion-star','Orion Star','Popular',1,2,'Orion Star - a popular player favourite. Create an account to play.'),
('milky-way','Milky Way','Slots',0,3,'Milky Way - a popular player favourite. Create an account to play.'),
('game-vault999','Game Vault999','Popular',0,4,'Game Vault999 - a popular player favourite. Create an account to play.'),
('panda-master','Panda Master','Slots',0,5,'Panda Master - a popular player favourite. Create an account to play.'),
('juwa','Juwa','Popular',0,6,'Juwa - a popular player favourite. Create an account to play.'),
('yolo-777','Yolo 777','Popular',0,7,'Yolo 777 - a popular player favourite. Create an account to play.'),
('game-room','Game Room','Popular',0,8,'Game Room - a popular player favourite. Create an account to play.'),
('cash-machine777','Cash Machine777','Slots',0,9,'Cash Machine777 - a popular player favourite. Create an account to play.'),
('juwa-2','Juwa 2','Popular',0,10,'Juwa 2 - a popular player favourite. Create an account to play.'),
('lucky-star','Lucky Star','Slots',0,11,'Lucky Star - a popular player favourite. Create an account to play.'),
('mr-all-one','Mr All One','Popular',0,12,'Mr All One - a popular player favourite. Create an account to play.'),
('cash-frenzy','Cash Frenzy','Slots',0,13,'Cash Frenzy - a popular player favourite. Create an account to play.'),
('ultra-panda','Ultra Panda','Slots',0,14,'Ultra Panda - a popular player favourite. Create an account to play.'),
('vblink','Vblink','Popular',1,15,'Vblink - a popular player favourite. Create an account to play.'),
('firekiran','Firekiran','Fish',1,16,'Firekiran - a popular fish game. Create an account to play.')
ON DUPLICATE KEY UPDATE name=VALUES(name), category=VALUES(category);
-- End of FireWin777 database v2 (20 tables).

-- Email verification: signups wait here until the 6-digit email code is
-- verified; the real account row in `users` is created only after that.
CREATE TABLE IF NOT EXISTS pending_verifications (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  first_name VARCHAR(60) DEFAULT NULL,
  last_name VARCHAR(60) DEFAULT NULL,
  username VARCHAR(30) DEFAULT NULL,
  email VARCHAR(190) NOT NULL,
  phone VARCHAR(40) DEFAULT NULL,
  password_hash VARCHAR(255) NOT NULL,
  device_fingerprint VARCHAR(190) DEFAULT NULL,
  referral_code VARCHAR(32) DEFAULT NULL,
  referred_by INT UNSIGNED DEFAULT NULL,
  signup_ip VARCHAR(45) DEFAULT NULL,
  city VARCHAR(120) DEFAULT NULL,
  country VARCHAR(120) DEFAULT NULL,
  address VARCHAR(255) DEFAULT NULL,
  verify_code VARCHAR(10) DEFAULT NULL,
  verify_expires DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_pending_email (email),
  KEY ix_pending_expires (verify_expires)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS checkin_claims (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  claim_date DATE NOT NULL,
  day_number TINYINT UNSIGNED NOT NULL,
  reward DECIMAL(10,2) NOT NULL DEFAULT 0,
  claimed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_user_date (user_id, claim_date),
  KEY idx_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-orders-tag.sql (orders.payer_tag (guarded))
-- ------------------------------------------------------------
-- Buy Coins payer tag: stores the customer's Cash App tag / Chime name /
-- card name on each order so the admin can match the payment to the sender.
-- Safe to re-run: the column is only added when it does not exist yet.
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'orders' AND COLUMN_NAME = 'payer_tag');
SET @sql := IF(@col = 0, 'ALTER TABLE orders ADD COLUMN payer_tag VARCHAR(120) NULL DEFAULT NULL AFTER email', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-bonus-claims.sql (bonus_claims table (claimed offers))
-- ------------------------------------------------------------
-- Claimed % offers: one row per claim. A claim pays its % on the player's
-- next approved deposit, directly into the main wallet, then is consumed.
-- Safe to re-run: the table is only created when it does not exist yet.
CREATE TABLE IF NOT EXISTS bonus_claims (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  offer_id VARCHAR(120) NOT NULL,
  offer_title VARCHAR(200) DEFAULT NULL,
  pct DECIMAL(6,2) NOT NULL DEFAULT 0,
  ends DATETIME DEFAULT NULL,
  status ENUM('claimed','consumed','replaced','expired') NOT NULL DEFAULT 'claimed',
  claimed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  consumed_at DATETIME DEFAULT NULL,
  order_id BIGINT UNSIGNED DEFAULT NULL,
  INDEX idx_bonus_claims_user (user_id),
  INDEX idx_bonus_claims_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-payment-methods.sql (payment_methods guards (no-op on this v2 base))
-- ------------------------------------------------------------
-- Payment methods repair: if the payment_methods table or any of its
-- columns is missing on the live database, the admin save fails and the
-- method never saves. This patch creates the table when it does not
-- exist, and adds each missing column when it does. Safe to re-run:
-- existing tables and columns are left untouched.
CREATE TABLE IF NOT EXISTS payment_methods (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  type VARCHAR(40) NOT NULL DEFAULT 'other',
  subtitle VARCHAR(200) DEFAULT NULL,
  icon VARCHAR(40) DEFAULT NULL,
  pill_text VARCHAR(80) DEFAULT NULL,
  qr_image_url VARCHAR(600) DEFAULT NULL,
  checkout_link VARCHAR(600) DEFAULT NULL,
  pay_label VARCHAR(80) NOT NULL DEFAULT 'Pay',
  min_amount DECIMAL(12,2) DEFAULT NULL,
  max_amount DECIMAL(12,2) DEFAULT NULL,
  instructions TEXT DEFAULT NULL,
  allow_withdraw TINYINT(1) NOT NULL DEFAULT 1,
  withdraw_subtitle VARCHAR(200) DEFAULT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  sort_order INT NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'name');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN name VARCHAR(120) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'type');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN type VARCHAR(40) NULL DEFAULT ''other''', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'subtitle');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN subtitle VARCHAR(200) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'icon');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN icon VARCHAR(40) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'pill_text');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN pill_text VARCHAR(80) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'qr_image_url');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN qr_image_url VARCHAR(600) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'checkout_link');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN checkout_link VARCHAR(600) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'pay_label');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN pay_label VARCHAR(80) NULL DEFAULT ''Pay''', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'min_amount');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN min_amount DECIMAL(12,2) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'max_amount');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN max_amount DECIMAL(12,2) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'instructions');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN instructions TEXT NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'allow_withdraw');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN allow_withdraw TINYINT(1) NULL DEFAULT 1', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'withdraw_subtitle');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN withdraw_subtitle VARCHAR(200) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'is_active');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN is_active TINYINT(1) NULL DEFAULT 1', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'sort_order');
SET @sql := IF(@col = 0, 'ALTER TABLE payment_methods ADD COLUMN sort_order INT NULL DEFAULT 0', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-signup-fields.sql (signup columns (guarded; base already has them))
-- ------------------------------------------------------------
-- FireWin777: new signup fields - First Name, Last Name, Username.
-- Adds the three columns to users and to pending_verifications (so the
-- email-code signup flow carries them through to the real account).
-- Safe to re-run: existing tables and columns are left untouched.
-- Old accounts keep working: the new columns are NULL for them, and the
-- backfill below fills first/last name from the existing full name.
-- Username is unique, but many NULLs are allowed, so old rows never clash.
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'first_name');
SET @sql := IF(@col = 0, 'ALTER TABLE users ADD COLUMN first_name VARCHAR(60) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'last_name');
SET @sql := IF(@col = 0, 'ALTER TABLE users ADD COLUMN last_name VARCHAR(60) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'username');
SET @sql := IF(@col = 0, 'ALTER TABLE users ADD COLUMN username VARCHAR(30) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @idx := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND INDEX_NAME = 'uq_users_username');
SET @sql := IF(@idx = 0, 'ALTER TABLE users ADD UNIQUE KEY uq_users_username (username)', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'pending_verifications' AND COLUMN_NAME = 'first_name');
SET @sql := IF(@col = 0, 'ALTER TABLE pending_verifications ADD COLUMN first_name VARCHAR(60) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'pending_verifications' AND COLUMN_NAME = 'last_name');
SET @sql := IF(@col = 0, 'ALTER TABLE pending_verifications ADD COLUMN last_name VARCHAR(60) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'pending_verifications' AND COLUMN_NAME = 'username');
SET @sql := IF(@col = 0, 'ALTER TABLE pending_verifications ADD COLUMN username VARCHAR(30) NULL DEFAULT NULL', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- Backfill first/last name for accounts created before these columns existed.
UPDATE users SET first_name = SUBSTRING_INDEX(name, ' ', 1) WHERE first_name IS NULL AND name IS NOT NULL AND name <> '';
UPDATE users SET last_name = NULLIF(TRIM(SUBSTRING(name, CHAR_LENGTH(SUBSTRING_INDEX(name, ' ', 1)) + 2)), '') WHERE last_name IS NULL AND name LIKE '% %';


-- ------------------------------------------------------------
-- MERGED PATCH: patch-game-accounts.sql (game_accounts + load/reset tables)
-- ------------------------------------------------------------
-- ============================================================
-- FireWin777 Phase 1: Game Accounts (auto + manual system)
-- Run ONCE in cPanel > phpMyAdmin on database hayatfirewin777_dbuser.
-- Safe to re-run: every statement is IF NOT EXISTS / ON DUPLICATE KEY.
-- The game-account system is fully per-game generic: one row per
-- player per game (game_slug), so it works for ALL games, not one.
-- ============================================================

-- 1) Player game accounts: one row per player per game.
-- status: 'processing' = player requested, admin has not provided yet
--         (the game page shows "processing" below Create Account);
--         'active' = admin provided username + password, player sees
--         them below Create Account on that game's page.
-- game_password_enc holds the password ENCRYPTED with the server
-- app_secret (AES-256-CBC, see api/game_accounts_lib.php) so it can
-- be shown back to its owner later. It is never stored in plain text.
CREATE TABLE IF NOT EXISTS game_accounts (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  game_slug VARCHAR(120) NOT NULL,
  game_name VARCHAR(160) NOT NULL DEFAULT '',
  game_username VARCHAR(120) DEFAULT NULL,
  game_password_enc TEXT DEFAULT NULL,
  status ENUM('processing','active') NOT NULL DEFAULT 'processing',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_ga_user_game (user_id, game_slug),
  INDEX idx_ga_user (user_id),
  INDEX idx_ga_status (status),
  CONSTRAINT fk_ga_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 2) Load requests: player asks to move money from their MAIN wallet
-- into one of their game accounts. NOTHING is cut at request time.
-- On admin Accept, the amount is cut from the main wallet and the
-- player sees "Your account has been recharged". On Reject, nothing
-- changes. (In Phase 2 auto mode, Accept happens automatically.)
CREATE TABLE IF NOT EXISTS game_load_requests (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  game_account_id BIGINT UNSIGNED NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  status ENUM('pending','accepted','rejected') NOT NULL DEFAULT 'pending',
  admin_note VARCHAR(500) DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  decided_at DATETIME DEFAULT NULL,
  decided_by INT UNSIGNED DEFAULT NULL,
  INDEX idx_glr_user (user_id),
  INDEX idx_glr_account (game_account_id),
  INDEX idx_glr_status (status),
  CONSTRAINT fk_glr_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_glr_account FOREIGN KEY (game_account_id) REFERENCES game_accounts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 3) Game password reset requests: player taps "Reset password" on a
-- game page. In manual mode the admin enters the new password; the
-- player then sees it below Create Account. (Phase 2 auto mode will
-- reset it in the store panel automatically.)
CREATE TABLE IF NOT EXISTS game_password_resets (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  game_account_id BIGINT UNSIGNED NOT NULL,
  status ENUM('pending','done','rejected') NOT NULL DEFAULT 'pending',
  admin_note VARCHAR(500) DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  decided_at DATETIME DEFAULT NULL,
  decided_by INT UNSIGNED DEFAULT NULL,
  INDEX idx_gpr_user (user_id),
  INDEX idx_gpr_account (game_account_id),
  INDEX idx_gpr_status (status),
  CONSTRAINT fk_gpr_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_gpr_account FOREIGN KEY (game_account_id) REFERENCES game_accounts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 4) Orders: a new status for auto-credited orders. When the
-- auto/manual switch is ON, approving a Buy Coins order credits the
-- wallet at once and the order becomes 'credited' (instead of
-- 'awaiting_admin_add'). The withdraw 4x rule counts 'credited'
-- orders as deposits (see api/withdrawals.php ws_total_deposits).
ALTER TABLE orders MODIFY status
  ENUM('pending','approved','awaiting_admin_add','credited','rejected')
  NOT NULL DEFAULT 'pending';

-- 5) Auto/manual switch seeds. Default is MANUAL ('0'): nothing
-- changes on the site until the admin flips it in Admin > Game
-- Accounts. Per-game keys (game_auto_mode_<slug>) override the
-- global key when present; absent = follow the global switch.
-- This INSERT never overwrites an existing value.
INSERT INTO site_settings (setting_key, setting_value) VALUES
  ('game_auto_mode', '0')
ON DUPLICATE KEY UPDATE setting_value = setting_value;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-game-accounts-status.sql (game_accounts status adds 'rejected' (after game-accounts))
-- ------------------------------------------------------------
-- Fix for "Reject (Server down)" error (2026-10-21):
-- The game_accounts table only allowed two states: 'processing' and 'active'.
-- Reject needs a third state, 'rejected'. Without it, the database refused
-- the Reject save and the admin panel showed an empty JSON error.
-- This adds 'rejected' to the list. Existing rows are NOT touched or deleted.
-- Safe to re-run.
ALTER TABLE game_accounts MODIFY status ENUM('processing','active','rejected') NOT NULL DEFAULT 'processing';


-- ------------------------------------------------------------
-- MERGED PATCH: patch-game-withdraw.sql (game_withdraw_requests table)
-- ------------------------------------------------------------
-- Game withdraw requests (Phase 1): player asks to move money FROM a game
-- account back to the MAIN wallet. Nothing is added at request time; the
-- add happens when the admin accepts (after redeeming in the store panel
-- by hand in manual mode). Safe to re-run (IF NOT EXISTS).
CREATE TABLE IF NOT EXISTS game_withdraw_requests (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  game_account_id BIGINT UNSIGNED NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  status ENUM('pending','accepted','rejected') NOT NULL DEFAULT 'pending',
  admin_note VARCHAR(500) DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  decided_at DATETIME DEFAULT NULL,
  decided_by INT UNSIGNED DEFAULT NULL,
  INDEX idx_gwr_user (user_id),
  INDEX idx_gwr_account (game_account_id),
  INDEX idx_gwr_status (status),
  CONSTRAINT fk_gwr_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  CONSTRAINT fk_gwr_account FOREIGN KEY (game_account_id) REFERENCES game_accounts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-auto-jobs.sql (auto_jobs + store_connections (worker heartbeat))
-- ------------------------------------------------------------
-- Phase 2 auto system: job queue + store connection status.
-- Safe to re-run (IF NOT EXISTS). No existing table is altered.
CREATE TABLE IF NOT EXISTS auto_jobs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  game_slug VARCHAR(120) NOT NULL,
  job_type ENUM('create','load','withdraw','reset') NOT NULL,
  ref_type VARCHAR(40) NOT NULL,
  ref_id INT NOT NULL,
  user_id INT NOT NULL,
  payload_json TEXT NULL,
  status ENUM('pending','claimed','done','failed') NOT NULL DEFAULT 'pending',
  attempts INT NOT NULL DEFAULT 0,
  result_json TEXT NULL,
  worker_note VARCHAR(255) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  claimed_at DATETIME NULL,
  INDEX (status, game_slug),
  INDEX (ref_type, ref_id)
);
CREATE TABLE IF NOT EXISTS store_connections (
  game_slug VARCHAR(120) PRIMARY KEY,
  status ENUM('never','connected','expired','down') NOT NULL DEFAULT 'never',
  last_check_at DATETIME NULL,
  last_error VARCHAR(255) NULL,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);


-- ------------------------------------------------------------
-- MERGED PATCH: patch-store-balance.sql (store balance columns (guarded; after auto-jobs))
-- ------------------------------------------------------------
-- Store balance on the heartbeat (connection proof).
-- Adds balance_text + balance_updated_at to store_connections.
-- The worker sends the store's own balance (e.g. YOLO "My Score")
-- with every connected heartbeat; any other state clears it, so a
-- shown balance always means "connected now".
-- Safe to re-run: each column is added only when missing.
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'store_connections' AND COLUMN_NAME = 'balance_text');
SET @sql = IF(@col_exists = 0, 'ALTER TABLE store_connections ADD COLUMN balance_text VARCHAR(64) NULL AFTER last_error', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'store_connections' AND COLUMN_NAME = 'balance_updated_at');
SET @sql = IF(@col_exists = 0, 'ALTER TABLE store_connections ADD COLUMN balance_updated_at DATETIME NULL AFTER balance_text', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-broadcast-email.sql (email_broadcasts + recipients + opt-out)
-- ------------------------------------------------------------
-- FireWin777: broadcast email (Brevo) — send email to all customers.
-- Run ONCE in phpMyAdmin. Safe to re-run: existing tables/columns are
-- left untouched.
CREATE TABLE IF NOT EXISTS email_broadcasts (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  subject VARCHAR(255) NOT NULL,
  body TEXT NOT NULL,
  status ENUM('sending','done') NOT NULL DEFAULT 'sending',
  total_recipients INT UNSIGNED NOT NULL DEFAULT 0,
  sent_count INT UNSIGNED NOT NULL DEFAULT 0,
  failed_count INT UNSIGNED NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS email_broadcast_recipients (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  broadcast_id BIGINT UNSIGNED NOT NULL,
  user_id INT UNSIGNED DEFAULT NULL,
  email VARCHAR(190) NOT NULL,
  status ENUM('pending','sent','failed') NOT NULL DEFAULT 'pending',
  error VARCHAR(255) DEFAULT NULL,
  sent_at DATETIME DEFAULT NULL,
  INDEX idx_br_broadcast (broadcast_id),
  INDEX idx_br_status (broadcast_id, status),
  CONSTRAINT fk_br_broadcast FOREIGN KEY (broadcast_id) REFERENCES email_broadcasts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- One-click unsubscribe flag on customers (guarded, safe to re-run).
SET @col := (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'email_opt_out');
SET @sql := IF(@col = 0, 'ALTER TABLE users ADD COLUMN email_opt_out TINYINT(1) NOT NULL DEFAULT 0', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-posts.sql (site_settings MEDIUMTEXT + posts_json row)
-- ------------------------------------------------------------
-- FireWin777 Posts: prepare the database for post saving (including gallery photos)
-- 1. Allow bigger saved data: post photos are stored compressed, but the old TEXT
--    limit (64KB) is too small for posts with photos. MEDIUMTEXT allows up to 16MB.
ALTER TABLE site_settings MODIFY setting_value MEDIUMTEXT;
-- 2. Make sure the posts storage row exists. If you already saved posts, this line
--    changes NOTHING (it keeps your saved posts safe).
INSERT INTO site_settings (setting_key, setting_value) VALUES ('posts_json', '[]')
ON DUPLICATE KEY UPDATE setting_value = setting_value;


-- ------------------------------------------------------------
-- MERGED PATCH: patch-fonts.sql (font colour settings rows)
-- ------------------------------------------------------------
INSERT INTO site_settings (setting_key, setting_value) VALUES
('font_family','system'),
('font_size','16'),
('font_color',''),
('heading_color','')
ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value);


-- ------------------------------------------------------------
-- MERGED PATCH (adapted from patch-game-images.sql):
-- game art URLs for the 12 live games that ship with art.
-- fire-kirin.jpg is NOT mapped to firekiran and vblink777.jpg
-- is NOT mapped to vblink (file names differ); set those two
-- in Admin -> Games. yolo-777 and mr-all-one ship without art.
-- ------------------------------------------------------------
UPDATE games SET image_url='/images/vegas-sweep.jpg' WHERE slug='vegas-sweep';
UPDATE games SET image_url='/images/orion-star.jpg' WHERE slug='orion-star';
UPDATE games SET image_url='/images/milky-way.jpg' WHERE slug='milky-way';
UPDATE games SET image_url='/images/game-vault999.jpg' WHERE slug='game-vault999';
UPDATE games SET image_url='/images/panda-master.jpg' WHERE slug='panda-master';
UPDATE games SET image_url='/images/juwa.jpg' WHERE slug='juwa';
UPDATE games SET image_url='/images/game-room.jpg' WHERE slug='game-room';
UPDATE games SET image_url='/images/cash-machine777.jpg' WHERE slug='cash-machine777';
UPDATE games SET image_url='/images/juwa-2.jpg' WHERE slug='juwa-2';
UPDATE games SET image_url='/images/lucky-star.jpg' WHERE slug='lucky-star';
UPDATE games SET image_url='/images/cash-frenzy.jpg' WHERE slug='cash-frenzy';
UPDATE games SET image_url='/images/ultra-panda.jpg' WHERE slug='ultra-panda';

-- ============================================================
-- FIREWIN UPDATE 2026-11-18 -- FireWin777 parity additions.
-- 22 new tables (13 instant-game score/history + 9 direct-API
-- store tables). Nothing here renames, drops or alters any of
-- the existing FireWin tables. All new tables use InnoDB +
-- utf8mb4, matching the rest of this file.
-- ============================================================

-- ------------------------------------------------------------
-- INSTANT GAMES (6 games x score row + history log)
-- Shape copied from FireWin: aviator (firewin777-aviator-score.sql),
-- plinko (plinko.sql), roulette (roulette.sql). Slot 777, Cashbull
-- and Joker 777 have NO .sql file in the FireWin set -- their
-- CREATE was never shipped as a file -- so they mirror the
-- aviator shape exactly (same columns the game APIs use:
-- slot777.php / cashbull.php / joker777.php lines 15-24).
-- Every *_score_tx.type is VARCHAR(20) from the start (NOT the
-- old ENUM('add','redeem','bet','win')): the 2026-11-04 FireWin
-- bug (patch-instant-score-type.sql) was that admin_add /
-- admin_remove and the 'forfeit' row on a full-6X redeem could
-- not save in strict MySQL and rolled back. VARCHAR(20) holds
-- add, redeem, bet, win, forfeit, admin_add, admin_remove.
-- wallet is 'main' or 'bonus' (Score split Main/Bonus).
-- The 4X/6X redeem rule reads the LATEST 'add' row per wallet
-- from these tx tables (see instant_admin.php / *_score_tx
-- queries), so do not prune old tx rows.
-- ------------------------------------------------------------

-- Slot 777
CREATE TABLE IF NOT EXISTS slot777_scores (
  user_id INT UNSIGNED NOT NULL PRIMARY KEY,
  main_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_slot777_scores_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS slot777_score_tx (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  wallet ENUM('main','bonus') NOT NULL,
  type VARCHAR(20) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  main_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_slot777_tx_user (user_id),
  INDEX idx_slot777_tx_created (created_at),
  CONSTRAINT fk_slot777_tx_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Cashbull
CREATE TABLE IF NOT EXISTS cashbull_scores (
  user_id INT UNSIGNED NOT NULL PRIMARY KEY,
  main_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_cashbull_scores_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS cashbull_score_tx (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  wallet ENUM('main','bonus') NOT NULL,
  type VARCHAR(20) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  main_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_cashbull_tx_user (user_id),
  INDEX idx_cashbull_tx_created (created_at),
  CONSTRAINT fk_cashbull_tx_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Joker 777
CREATE TABLE IF NOT EXISTS joker777_scores (
  user_id INT UNSIGNED NOT NULL PRIMARY KEY,
  main_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_joker777_scores_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS joker777_score_tx (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  wallet ENUM('main','bonus') NOT NULL,
  type VARCHAR(20) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  main_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_joker777_tx_user (user_id),
  INDEX idx_joker777_tx_created (created_at),
  CONSTRAINT fk_joker777_tx_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Aviator (copied from FireWin firewin777-aviator-score.sql,
-- except score_tx.type is VARCHAR(20) -- see note above --
-- instead of the original ENUM('add','redeem','bet','win')).
CREATE TABLE IF NOT EXISTS aviator_scores (
  user_id INT UNSIGNED NOT NULL PRIMARY KEY,
  main_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_aviator_scores_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS aviator_score_tx (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  wallet ENUM('main','bonus') NOT NULL,
  type VARCHAR(20) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  main_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  bonus_score_after DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_aviator_tx_user (user_id),
  INDEX idx_aviator_tx_created (created_at),
  CONSTRAINT fk_aviator_tx_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS aviator_rounds (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  wallet VARCHAR(10) NOT NULL DEFAULT 'main',
  bet DECIMAL(10,2) NOT NULL,
  crash_point DECIMAL(10,2) NOT NULL,
  crash_duration DECIMAL(10,3) NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'pending',
  start_time DATETIME NULL,
  cashout_multiplier DECIMAL(10,2) NULL,
  win DECIMAL(10,2) NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_aviator_rounds_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Plinko (copied from FireWin plinko.sql; ENGINE/charset added,
-- the FireWin file omits them -- columns unchanged).
CREATE TABLE IF NOT EXISTS plinko_scores (
  user_id INT NOT NULL PRIMARY KEY,
  main_score DECIMAL(12,2) NOT NULL DEFAULT 0,
  bonus_score DECIMAL(12,2) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS plinko_score_tx (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  wallet VARCHAR(10) NOT NULL,
  type VARCHAR(20) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  main_score_after DECIMAL(12,2) NOT NULL DEFAULT 0,
  bonus_score_after DECIMAL(12,2) NOT NULL DEFAULT 0,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_plinko_tx_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Roulette (copied from FireWin roulette.sql; ENGINE/charset
-- added, the FireWin file omits them -- columns unchanged).
CREATE TABLE IF NOT EXISTS roulette_scores (
  user_id INT NOT NULL PRIMARY KEY,
  main_score DECIMAL(12,2) NOT NULL DEFAULT 0,
  bonus_score DECIMAL(12,2) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS roulette_score_tx (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  wallet VARCHAR(10) NOT NULL,
  type VARCHAR(20) NOT NULL,
  amount DECIMAL(12,2) NOT NULL,
  main_score_after DECIMAL(12,2) NOT NULL DEFAULT 0,
  bonus_score_after DECIMAL(12,2) NOT NULL DEFAULT 0,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_roulette_tx_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ------------------------------------------------------------
-- DIRECT-API STORE TABLES (Yolo 777 / Fire Kirin / Game Vault)
-- Copied from FireWin yolo.sql, firekirin.sql, gamevault.sql.
-- These are the tables the direct store APIs use (api/yolo.php,
-- api/firekirin.php, api/gamevault.php on FireWin): one player
-- link row per customer, a throttle row so the store rate limit
-- is respected, and an append-only event log shown in the admin
-- store panel. Only needed if FireWin adopts the direct-API
-- game panels; harmless if unused. (FireWin already has
-- auto_jobs + store_connections from the older worker system;
-- these 9 tables are separate and do not replace them.)
-- ------------------------------------------------------------

-- Yolo 777
CREATE TABLE IF NOT EXISTS yolo_players (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  yolo_user_id BIGINT UNSIGNED NOT NULL,
  account VARCHAR(120) NOT NULL DEFAULT '',
  balance DECIMAL(12,2) NOT NULL DEFAULT 0,
  last_sync_at DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_yp_user (user_id),
  UNIQUE KEY uq_yp_yolo (yolo_user_id),
  INDEX idx_yp_account (account),
  CONSTRAINT fk_yp_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS yolo_throttle (
  yolo_user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
  last_call_ms BIGINT UNSIGNED NOT NULL,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS yolo_log (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  yolo_user_id BIGINT UNSIGNED DEFAULT NULL,
  event VARCHAR(40) NOT NULL,
  detail TEXT DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_yl_user (yolo_user_id),
  INDEX idx_yl_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Fire Kirin
CREATE TABLE IF NOT EXISTS fk_players (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  account VARCHAR(64) NOT NULL DEFAULT '',
  balance DECIMAL(12,2) NOT NULL DEFAULT 0,
  last_sync_at DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_fk_user (user_id),
  UNIQUE KEY uq_fk_account (account),
  CONSTRAINT fk_fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS fk_throttle (
  scope VARCHAR(20) NOT NULL PRIMARY KEY,
  last_call_ms BIGINT UNSIGNED NOT NULL,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS fk_log (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  account VARCHAR(64) DEFAULT NULL,
  event VARCHAR(40) NOT NULL,
  detail TEXT DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_fk_account (account),
  INDEX idx_fk_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Game Vault
CREATE TABLE IF NOT EXISTS gv_players (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id INT UNSIGNED NOT NULL,
  account VARCHAR(64) NOT NULL DEFAULT '',
  gv_user_id VARCHAR(64) NOT NULL DEFAULT '',
  balance VARCHAR(64) NOT NULL DEFAULT '0',
  last_sync_at DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_gv_user (user_id),
  UNIQUE KEY uq_gv_account (account),
  UNIQUE KEY uq_gv_gvuser (gv_user_id),
  CONSTRAINT fk_gv_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS gv_throttle (
  scope VARCHAR(20) NOT NULL PRIMARY KEY,
  last_call_ms BIGINT UNSIGNED NOT NULL,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS gv_log (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  account VARCHAR(64) DEFAULT NULL,
  event VARCHAR(40) NOT NULL,
  detail TEXT DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_gv_account (account),
  INDEX idx_gv_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
