-- Chon Stay Platform, MySQL schema for Namecheap cPanel.
-- Import this file in phpMyAdmin, into the database created in cPanel
-- on Nov 11, 2026: certivgm_chonpms, user certivgm_chonpms.
-- It creates the same five tables the Muse platform uses, with the
-- same columns and the same meaning, translated from SQLite to MySQL,
-- plus the two ledger tables added in v6 (expense_categories and
-- expenses) with the 21 USALI-lite accounts seeded, plus the three
-- connector tables added in v7 (connectors, connector_sync_logs,
-- connector_conflicts), plus the two other-revenue tables added in
-- v8 (revenue_categories and revenues) with the 4 revenue accounts,
-- v11.1 adds a fifth, 4001 Room Revenue, in a new 'rooms' group
-- seeded, plus the two bank-activity tables added in v9
-- (bank_mapping_rules and bank_transactions) and the source column
-- on expenses and revenues, which marks bank-imported entries,
-- plus the thirteen money-correctness tables added in v10
-- (pms_settings, folios, folio_lines, folio_payments,
-- folio_adjustments, invoices, audit_pack, tills, petty_cash,
-- currency_log, company_accounts, company_transactions, audit_log),
-- plus the twenty-one operations tables added in v11
-- (housekeeping_tasks, housekeeping_defects, guests, guest_merges,
-- id_captures, groups, group_rooms, pos_tables, pos_menu_items,
-- pos_bills, pos_bill_items, pos_bill_payments, rate_seasons,
-- rate_season_rooms, rate_plans, meal_plans, vouchers,
-- rate_guardrails, rate_rules, report_budgets, report_snapshots)
-- and the six v11 columns on bookings (guest_id, group_id,
-- rate_plan_id, meal_plan_id, voucher_code, price_json), plus the
-- eighteen connect-and-automate tables added in v12
-- (sync_revisions, reconciliation_runs, reconciliation_diffs,
-- ical_push_tokens, ical_push_log, automation_rules,
-- automation_runs, notifications, ledger_notes, message_templates,
-- messaging_providers, message_outbox, message_threads,
-- message_items, api_tokens, smart_lock_providers,
-- smart_lock_events, config_snapshots), plus the four
-- finish-the-hooks tables added in v13 (email_schedules,
-- email_send_log, receipts, checkin_tokens) and the
-- pre_checked_in column on bookings.
-- The connectors table carries the v8 provider_kind and
-- display_name columns for custom providers. The bookings table
-- also carries the v7 external id columns and the two import sources
-- in its source ENUM. The server creates the connector, ledger, bank,
-- money and operations tables itself on startup too, so a fresh
-- install and an upgrade end up with the same tables either way.
-- Timestamps are stored as BIGINT milliseconds since the epoch, the
-- same as the Muse app, so the server can convert them to ISO dates.
-- All text is utf8mb4, so Vietnamese names store correctly.
-- Upgrading an existing install does NOT need this file: the server
-- creates the new tables itself on its first start after the v11
-- upgrade, and adds the missing columns to the tables that already
-- exist. Do NOT re-import it on a live database.

-- Users who can log in to the platform. role is admin or staff.
-- password_hash is a PBKDF2 hash in the form saltHex:hashHex, never
-- plain text. active 1 means the user can log in, 0 means deactivated.
CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(80) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  role VARCHAR(32) NOT NULL DEFAULT 'staff',
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Login sessions. token is a random 64 character hex string.
-- A session is deleted on logout, when the user is deactivated or
-- deleted, and when the user's password is changed by an admin.
CREATE TABLE IF NOT EXISTS sessions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  token VARCHAR(128) NOT NULL UNIQUE,
  user_id INT NOT NULL,
  created_at BIGINT NOT NULL,
  CONSTRAINT fk_sessions_user FOREIGN KEY (user_id)
    REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Password reset requests from the Forgot password link on the login
-- page. No email is sent. The admin sees pending requests in Users and
-- resets the password there. user_id is NULL when no account exists
-- with that username, the request is kept for history.
CREATE TABLE IF NOT EXISTS password_reset_requests (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(80) NOT NULL,
  user_id INT NULL,
  status ENUM('pending', 'done') NOT NULL DEFAULT 'pending',
  created_at BIGINT NOT NULL,
  resolved_at BIGINT NULL,
  CONSTRAINT fk_reset_user FOREIGN KEY (user_id)
    REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- The 7 real rooms of Chon Boutique Stay. balcony 1 means the room has
-- a balcony, 0 means it does not. Only Blue (floor 7) has a balcony
-- (corrected Nov 21, 2026). Vivid, Euphoria, Dreamscape, Still, and
-- Dune have an indoor sitting room next to the window view, not a
-- balcony. Sanctuary has no balcony, no view, and no sitting room by
-- a window view.
-- housekeeping_status is clean, dirty, in_progress, inspected, or
-- out_of_order. rate_vnd is the nightly rate in VND, VAT included.
CREATE TABLE IF NOT EXISTS rooms (
  id INT AUTO_INCREMENT PRIMARY KEY,
  slug VARCHAR(40) NOT NULL UNIQUE,
  name_en VARCHAR(80) NOT NULL,
  name_vi VARCHAR(80) NOT NULL,
  floor INT NOT NULL,
  rate_vnd INT NOT NULL,
  palette VARCHAR(16) NOT NULL,
  balcony TINYINT(1) NOT NULL DEFAULT 1,
  housekeeping_status ENUM('dirty', 'in_progress', 'needs_inspection', 'clean', 'out_of_order') NOT NULL DEFAULT 'clean'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Bookings. check_in and check_out are dates, YYYY-MM-DD. A booking
-- blocks the room from check_in up to, but not including, check_out.
-- source is direct, walk_in, phone, email, airbnb, expedia,
-- booking_com, agoda, ical, or beds24. The last two are import
-- sources (v7): a booking pulled from an iCal feed, or from Beds24
-- when the channel is not one of the four named OTAs. status is
-- confirmed, checked_in, checked_out, cancelled, or no_show.
-- payment_status is unpaid, deposit, paid, or refunded. total_vnd is
-- the total at booking time and never changes when rates change
-- later. external_provider and external_id (v7) identify the booking
-- in the system it was pulled from, for example "beds24" and
-- "beds24:1234567", or "ical" and "ical:sanctuary:abc123". The
-- unique index on the pair makes a pull idempotent: re-pulling the
-- same booking never duplicates it. Manual bookings have NULL in
-- both columns, and MySQL allows many NULLs in a unique index, so
-- they are unaffected. The v11 columns link the booking to its
-- guest record (guest_id), its group (group_id), the rate and meal
-- plan it was priced with (rate_plan_id, meal_plan_id), the voucher
-- code used (voucher_code), and the price breakdown as JSON
-- (price_json), so the booking detail can show how the total was
-- reached without re-running the engine.
CREATE TABLE IF NOT EXISTS bookings (
  id INT AUTO_INCREMENT PRIMARY KEY,
  room_id INT NOT NULL,
  guest_name VARCHAR(120) NOT NULL,
  guest_email VARCHAR(160) NOT NULL DEFAULT '',
  guest_phone VARCHAR(40) NOT NULL DEFAULT '',
  check_in DATE NOT NULL,
  check_out DATE NOT NULL,
  guests INT NOT NULL DEFAULT 2,
  extra_beds INT NOT NULL DEFAULT 0,
  source ENUM('direct', 'walk_in', 'phone', 'email', 'airbnb', 'expedia', 'booking_com', 'agoda', 'ical', 'beds24') NOT NULL DEFAULT 'direct',
  status ENUM('confirmed', 'checked_in', 'checked_out', 'cancelled', 'no_show') NOT NULL DEFAULT 'confirmed',
  payment_status ENUM('unpaid', 'deposit', 'paid', 'refunded') NOT NULL DEFAULT 'unpaid',
  total_vnd INT NOT NULL,
  notes TEXT NOT NULL DEFAULT '',
  external_provider VARCHAR(40) NULL,
  external_id VARCHAR(120) NULL,
  guest_id INT NULL,
  group_id INT NULL,
  rate_plan_id INT NULL,
  meal_plan_id INT NULL,
  voucher_code VARCHAR(40) NULL,
  price_json TEXT NULL,
  last_imported_at BIGINT NULL,
  last_imported_hash VARCHAR(64) NULL,
  local_modified_at BIGINT NULL,
  external_revision INT NOT NULL DEFAULT 0,
  pre_checked_in TINYINT(1) NOT NULL DEFAULT 0,
  created_at BIGINT NOT NULL,
  CONSTRAINT fk_bookings_room FOREIGN KEY (room_id)
    REFERENCES rooms (id) ON DELETE RESTRICT,
  INDEX idx_bookings_room_dates (room_id, check_in, check_out, status),
  UNIQUE INDEX ux_bookings_external (external_provider, external_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Connectors (v7 pull framework, v8 custom providers). One row per
-- connector card on the Connectors page. provider_kind is what the
-- pull engine dispatches on: for a built-in provider it equals the
-- connector key (beds24, ical, asiapay, momo, paypal); for a custom
-- provider it is custom_ical (a named iCal feed set) or
-- custom_payment (name and account details stored for later), and
-- display_name holds the admin's name for it. config_json holds
-- non-secret settings only: the iCal feed URL per room, the Beds24
-- property id, a payment merchant id stored for later. secret_enc
-- holds the encrypted JSON of API keys and tokens (AES-256-GCM, key
-- from CHON_CONNECTOR_KEY); secret_hint is only the masked last 4
-- characters, for display. status is not_connected, connected, or
-- error. last_sync_* describe the most recent sync run; the full
-- history is in connector_sync_logs.
CREATE TABLE IF NOT EXISTS connectors (
  id INT AUTO_INCREMENT PRIMARY KEY,
  connector_key VARCHAR(40) NOT NULL UNIQUE,
  connector_group ENUM('reservations', 'payments') NOT NULL,
  provider_kind VARCHAR(20) NOT NULL DEFAULT '',
  display_name VARCHAR(80) NOT NULL DEFAULT '',
  config_json TEXT NOT NULL DEFAULT '',
  secret_enc TEXT NOT NULL DEFAULT '',
  secret_hint VARCHAR(16) NOT NULL DEFAULT '',
  status VARCHAR(20) NOT NULL DEFAULT 'not_connected',
  enabled TINYINT(1) NOT NULL DEFAULT 1,
  last_sync_at BIGINT NULL,
  last_sync_status VARCHAR(20) NULL,
  last_sync_error TEXT NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- One row per sync run, success or error, so the Connectors page can
-- show what each pull did: how many external bookings were pulled,
-- how many were created, updated, skipped, or conflicted.
CREATE TABLE IF NOT EXISTS connector_sync_logs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  connector_id INT NOT NULL,
  provider VARCHAR(40) NOT NULL,
  started_at BIGINT NOT NULL,
  finished_at BIGINT NULL,
  status ENUM('running', 'success', 'error') NOT NULL DEFAULT 'running',
  pulled INT NOT NULL DEFAULT 0,
  created INT NOT NULL DEFAULT 0,
  updated INT NOT NULL DEFAULT 0,
  skipped INT NOT NULL DEFAULT 0,
  conflicts INT NOT NULL DEFAULT 0,
  error TEXT NOT NULL DEFAULT '',
  details TEXT NOT NULL DEFAULT '',
  INDEX idx_sync_logs_connector (connector_id, started_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Sync conflicts (v7). An imported booking that would overlap a live
-- booking for the same room is NOT imported: it is recorded here and
-- surfaced on the Connectors page, so a room can never be
-- double-booked by a sync. resolved is set when the admin marks it
-- resolved after fixing the dates in the source or cancelling the
-- blocking booking.
CREATE TABLE IF NOT EXISTS connector_conflicts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  connector_id INT NOT NULL,
  provider VARCHAR(40) NOT NULL,
  room_id INT NOT NULL,
  external_id VARCHAR(120) NOT NULL DEFAULT '',
  guest_name VARCHAR(120) NOT NULL DEFAULT '',
  check_in DATE NOT NULL,
  check_out DATE NOT NULL,
  conflicting_booking_id INT NULL,
  reason VARCHAR(255) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  resolved TINYINT(1) NOT NULL DEFAULT 0,
  INDEX idx_conflicts_connector (connector_id, resolved)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Expense ledger (v6). The chart of accounts is USALI-lite: 21
-- accounts in the 5000 series, grouped by department. Rooms and
-- Food & Beverage are the operated departments (F&B is Ve Cafe),
-- the rest are undistributed operating expenses, non-operating, or
-- Miscellaneous (v8, account 5801, for costs that fit no other
-- account). is_labor marks the accounts that are labor by nature;
-- the flag is still stored per expense entry, because one account
-- can hold both labor and non-labor costs, and hotel reporting
-- needs the split.
CREATE TABLE IF NOT EXISTS expense_categories (
  id INT AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(10) NOT NULL UNIQUE,
  department ENUM('rooms', 'fb', 'ag', 'sm', 'pom', 'util', 'nonop', 'misc') NOT NULL,
  name_en VARCHAR(80) NOT NULL,
  name_vi VARCHAR(80) NOT NULL,
  is_labor TINYINT(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Expense entries. Amounts are stored in VND; the frontend displays
-- USD in EN mode and VND in VI mode, at 25,600 VND per USD.
-- status is pending, approved, or rejected. Staff entries start
-- pending; entries added by an admin are approved straight away.
-- submitted_by_name and approved_by_name are kept as text, so the
-- audit trail still names the person even if their account is
-- deleted later. receipt_ref is a receipt or invoice number only:
-- there is no receipt file upload in v6.
CREATE TABLE IF NOT EXISTS expenses (
  id INT AUTO_INCREMENT PRIMARY KEY,
  expense_date DATE NOT NULL,
  vendor VARCHAR(120) NOT NULL DEFAULT '',
  description VARCHAR(255) NOT NULL DEFAULT '',
  category_id INT NOT NULL,
  is_labor TINYINT(1) NOT NULL DEFAULT 0,
  amount_vnd INT NOT NULL,
  vat_vnd INT NOT NULL DEFAULT 0,
  payment_method ENUM('cash', 'bank_transfer', 'card', 'momo', 'other') NOT NULL DEFAULT 'cash',
  payment_status ENUM('paid', 'unpaid') NOT NULL DEFAULT 'unpaid',
  receipt_ref VARCHAR(120) NOT NULL DEFAULT '',
  outlet ENUM('hotel', 'cafe') NOT NULL DEFAULT 'hotel',
  submitted_by INT NULL,
  submitted_by_name VARCHAR(80) NOT NULL DEFAULT '',
  status ENUM('pending', 'approved', 'rejected') NOT NULL DEFAULT 'pending',
  approved_by INT NULL,
  approved_by_name VARCHAR(80) NOT NULL DEFAULT '',
  approved_at BIGINT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  source VARCHAR(20) NOT NULL DEFAULT 'manual',
  CONSTRAINT fk_expenses_category FOREIGN KEY (category_id)
    REFERENCES expense_categories (id) ON DELETE RESTRICT,
  CONSTRAINT fk_expenses_submitted_by FOREIGN KEY (submitted_by)
    REFERENCES users (id) ON DELETE SET NULL,
  CONSTRAINT fk_expenses_approved_by FOREIGN KEY (approved_by)
    REFERENCES users (id) ON DELETE SET NULL,
  INDEX idx_expenses_date (expense_date),
  INDEX idx_expenses_category (category_id),
  INDEX idx_expenses_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- The USALI-lite chart of accounts, 21 accounts. INSERT IGNORE makes
-- re-importing this file safe, and the server seeds the same list
-- itself when rows are missing.
INSERT IGNORE INTO expense_categories (code, department, name_en, name_vi, is_labor) VALUES
  ('5001', 'rooms', 'Housekeeping Salaries and Wages', 'Lương dọn phòng', 1),
  ('5002', 'rooms', 'Housekeeping Supplies', 'Vật tư dọn phòng', 0),
  ('5003', 'rooms', 'Guest Supplies and Amenities', 'Vật dụng cho khách', 0),
  ('5004', 'rooms', 'Linen and Laundry', 'Vải lanh và giặt ủi', 0),
  ('5101', 'fb', 'Food Cost', 'Chi phí thực phẩm', 0),
  ('5102', 'fb', 'Beverage Cost', 'Chi phí đồ uống', 0),
  ('5103', 'fb', 'Kitchen Supplies', 'Vật tư bếp', 0),
  ('5104', 'fb', 'Cafe Salaries and Wages', 'Lương nhân viên cafe', 1),
  ('5301', 'ag', 'Office Supplies', 'Văn phòng phẩm', 0),
  ('5302', 'ag', 'Professional Fees', 'Phí dịch vụ chuyên môn', 0),
  ('5303', 'ag', 'Licenses and Permits', 'Giấy phép', 0),
  ('5401', 'sm', 'Advertising and Promotion', 'Quảng cáo và khuyến mãi', 0),
  ('5402', 'sm', 'OTA Commissions', 'Hoa hồng kênh đặt phòng', 0),
  ('5501', 'pom', 'Repairs and Maintenance', 'Sửa chữa và bảo trì', 0),
  ('5502', 'pom', 'Maintenance Supplies', 'Vật tư bảo trì', 0),
  ('5601', 'util', 'Electricity', 'Điện', 0),
  ('5602', 'util', 'Water', 'Nước', 0),
  ('5603', 'util', 'Internet and Telecom', 'Internet và viễn thông', 0),
  ('5604', 'util', 'Gas', 'Gas', 0),
  ('5701', 'nonop', 'Insurance', 'Bảo hiểm', 0),
  ('5801', 'misc', 'Miscellaneous Expenses', 'Chi phí khác', 0);

-- Other revenue (v8). Five revenue accounts in the 4000 series,
-- grouped for the monthly summary: "fb" is Ve Cafe food and
-- beverage revenue, "other" is everything else that is not room
-- bookings, and "rooms" (v11.1) is room revenue, account 4001, the
-- cash receipt of OTA and Beds24 payouts. A 4001 entry is the cash
-- receipt of revenue already counted in the summary's Room revenue
-- line (computed from bookings), so it never adds to the summary's
-- Room, F&B, Other, or Total revenue. Revenue entries mirror
-- expenses: same approval model (Staff add pending, admin
-- approves, rejects, edits, deletes) and same audit trail, but no
-- vendor, no VAT, no labor flag, and no payment method or status,
-- because revenue is money already received. Only approved revenue
-- counts towards GOP.
CREATE TABLE IF NOT EXISTS revenue_categories (
  id INT AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(10) NOT NULL UNIQUE,
  revenue_group ENUM('rooms', 'fb', 'other') NOT NULL,
  name_en VARCHAR(80) NOT NULL,
  name_vi VARCHAR(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS revenues (
  id INT AUTO_INCREMENT PRIMARY KEY,
  revenue_date DATE NOT NULL,
  category_id INT NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  amount_vnd INT NOT NULL,
  outlet ENUM('hotel', 'cafe') NOT NULL DEFAULT 'hotel',
  submitted_by INT NULL,
  submitted_by_name VARCHAR(80) NOT NULL DEFAULT '',
  status ENUM('pending', 'approved', 'rejected') NOT NULL DEFAULT 'pending',
  approved_by INT NULL,
  approved_by_name VARCHAR(80) NOT NULL DEFAULT '',
  approved_at BIGINT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  source VARCHAR(20) NOT NULL DEFAULT 'manual',
  CONSTRAINT fk_revenues_category FOREIGN KEY (category_id)
    REFERENCES revenue_categories (id) ON DELETE RESTRICT,
  CONSTRAINT fk_revenues_submitted_by FOREIGN KEY (submitted_by)
    REFERENCES users (id) ON DELETE SET NULL,
  CONSTRAINT fk_revenues_approved_by FOREIGN KEY (approved_by)
    REFERENCES users (id) ON DELETE SET NULL,
  INDEX idx_revenues_date (revenue_date),
  INDEX idx_revenues_category (category_id),
  INDEX idx_revenues_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO revenue_categories (code, revenue_group, name_en, name_vi) VALUES
  ('4001', 'rooms', 'Room Revenue', 'Doanh thu phòng'),
  ('4101', 'fb', 'Food Revenue', 'Doanh thu thực phẩm'),
  ('4102', 'fb', 'Beverage Revenue', 'Doanh thu đồ uống'),
  ('4201', 'other', 'Other Operated Revenue', 'Doanh thu hoạt động khác'),
  ('4301', 'other', 'Miscellaneous Income', 'Thu nhập khác');

-- Bank activity (v9). bank_mapping_rules holds the admin's
-- description-to-account rules: when a bank transaction description
-- contains the rule text, it posts to that account automatically, as
-- a pending entry. bank_transactions holds every bank transaction
-- once: the unique index on (source, external_id) makes the SePay
-- pull idempotent (a webhook and a Sync pull of the same SePay
-- transaction id store one row), and the unique index on
-- dedupe_hash makes statement import idempotent (date, direction,
-- amount and reference, so a re-uploaded file never double-imports).
-- The source column on expenses and revenues above marks entries
-- that came from the bank ('sepay' or 'statement') versus entries
-- typed in by hand ('manual').
CREATE TABLE IF NOT EXISTS bank_mapping_rules (
  id INT AUTO_INCREMENT PRIMARY KEY,
  direction ENUM('in', 'out') NOT NULL,
  match_text VARCHAR(120) NOT NULL,
  account_type ENUM('expense', 'revenue') NOT NULL,
  category_id INT NOT NULL,
  priority INT NOT NULL DEFAULT 100,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_bank_rules_direction (direction, priority)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS bank_transactions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  source ENUM('sepay', 'statement') NOT NULL,
  provider VARCHAR(40) NOT NULL DEFAULT '',
  external_id VARCHAR(120) NULL,
  txn_date DATE NOT NULL,
  direction ENUM('in', 'out') NOT NULL,
  amount_vnd INT NOT NULL,
  description TEXT NOT NULL DEFAULT '',
  reference_code VARCHAR(120) NOT NULL DEFAULT '',
  account_number VARCHAR(40) NOT NULL DEFAULT '',
  raw_json TEXT NOT NULL DEFAULT '',
  dedupe_hash VARCHAR(64) NOT NULL,
  status ENUM('queued', 'posted', 'ignored') NOT NULL DEFAULT 'queued',
  expense_id INT NULL,
  revenue_id INT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  UNIQUE INDEX ux_bank_external (source, external_id),
  UNIQUE INDEX ux_bank_dedupe (dedupe_hash),
  INDEX idx_bank_status_date (status, txn_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Money correctness (v10). pms_settings holds the business date
-- and the VAT rate. folios is one folio per stay, auto-opened at
-- check-in; folio_lines is append-only (a void only flips the
-- status flag and posts a reversing line); folio_payments records
-- payments against a folio; folio_adjustments holds void and
-- discount requests waiting for an admin decision; invoices holds
-- the numbered invoice created at settlement. audit_pack holds one
-- snapshot per closed business date, which makes the night audit
-- idempotent. tills, petty_cash and currency_log are the cashier
-- records. company_accounts and company_transactions are the city
-- ledger. audit_log records every state-changing action.
CREATE TABLE IF NOT EXISTS pms_settings (
  setting_key VARCHAR(40) NOT NULL PRIMARY KEY,
  setting_value TEXT NOT NULL DEFAULT '',
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS folios (
  id INT AUTO_INCREMENT PRIMARY KEY,
  booking_id INT NOT NULL UNIQUE,
  status ENUM('open', 'settled') NOT NULL DEFAULT 'open',
  opened_by INT NULL,
  opened_by_name VARCHAR(80) NOT NULL DEFAULT '',
  opened_at BIGINT NOT NULL,
  settled_at BIGINT NULL,
  settled_by INT NULL,
  settled_by_name VARCHAR(80) NOT NULL DEFAULT '',
  invoice_id INT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_folios_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS folio_lines (
  id INT AUTO_INCREMENT PRIMARY KEY,
  folio_id INT NOT NULL,
  line_date DATE NOT NULL,
  line_type ENUM('room_night', 'extra_bed', 'charge', 'adjustment', 'discount') NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  amount_vnd INT NOT NULL,
  vat_vnd INT NOT NULL DEFAULT 0,
  routed_to ENUM('guest', 'company') NOT NULL DEFAULT 'guest',
  company_account_id INT NULL,
  status ENUM('posted', 'voided') NOT NULL DEFAULT 'posted',
  reverses_line_id INT NULL,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_folio_lines_folio (folio_id, line_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS folio_payments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  folio_id INT NOT NULL,
  payment_date DATE NOT NULL,
  method ENUM('cash', 'card', 'bank_transfer') NOT NULL,
  amount_vnd INT NOT NULL,
  reference VARCHAR(120) NOT NULL DEFAULT '',
  received_by INT NULL,
  received_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_folio_payments_folio (folio_id, payment_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS folio_adjustments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  folio_id INT NOT NULL,
  kind ENUM('void', 'discount') NOT NULL,
  folio_line_id INT NULL,
  amount_vnd INT NOT NULL,
  reason_code VARCHAR(40) NOT NULL DEFAULT '',
  reason VARCHAR(255) NOT NULL DEFAULT '',
  status ENUM('pending', 'approved', 'rejected') NOT NULL DEFAULT 'pending',
  requested_by INT NULL,
  requested_by_name VARCHAR(80) NOT NULL DEFAULT '',
  requested_at BIGINT NOT NULL,
  decided_by INT NULL,
  decided_by_name VARCHAR(80) NOT NULL DEFAULT '',
  decided_at BIGINT NULL,
  INDEX idx_folio_adj_status (status, requested_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS invoices (
  id INT AUTO_INCREMENT PRIMARY KEY,
  folio_id INT NOT NULL UNIQUE,
  invoice_number VARCHAR(20) NOT NULL UNIQUE,
  issued_at BIGINT NOT NULL,
  guest_total_vnd INT NOT NULL,
  company_total_vnd INT NOT NULL,
  payments_total_vnd INT NOT NULL,
  balance_due_vnd INT NOT NULL,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS audit_pack (
  id INT AUTO_INCREMENT PRIMARY KEY,
  business_date DATE NOT NULL UNIQUE,
  run_at BIGINT NOT NULL,
  run_by INT NULL,
  run_by_name VARCHAR(80) NOT NULL DEFAULT '',
  trigger ENUM('manual', 'scheduled') NOT NULL DEFAULT 'manual',
  occupancy_rooms INT NOT NULL DEFAULT 0,
  arrivals INT NOT NULL DEFAULT 0,
  departures INT NOT NULL DEFAULT 0,
  rooms_revenue_vnd INT NOT NULL DEFAULT 0,
  payments_vnd INT NOT NULL DEFAULT 0,
  folio_balance_vnd INT NOT NULL DEFAULT 0,
  till_total_vnd INT NOT NULL DEFAULT 0,
  no_shows INT NOT NULL DEFAULT 0,
  details_json TEXT NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS tills (
  id INT AUTO_INCREMENT PRIMARY KEY,
  opened_by INT NULL,
  opened_by_name VARCHAR(80) NOT NULL DEFAULT '',
  opened_at BIGINT NOT NULL,
  opening_float_vnd INT NOT NULL,
  status ENUM('open', 'closed') NOT NULL DEFAULT 'open',
  closed_by INT NULL,
  closed_by_name VARCHAR(80) NOT NULL DEFAULT '',
  closed_at BIGINT NULL,
  counted_cash_vnd INT NULL,
  expected_cash_vnd INT NULL,
  variance_vnd INT NULL,
  variance_note VARCHAR(255) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_tills_status (status, opened_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS petty_cash (
  id INT AUTO_INCREMENT PRIMARY KEY,
  cash_date DATE NOT NULL,
  reason VARCHAR(255) NOT NULL DEFAULT '',
  amount_vnd INT NOT NULL,
  category_id INT NULL,
  expense_id INT NULL,
  paid_by INT NULL,
  paid_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_petty_cash_date (cash_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS currency_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  log_date DATE NOT NULL,
  currency VARCHAR(10) NOT NULL,
  foreign_amount_minor INT NOT NULL,
  rate_vnd INT NOT NULL,
  vnd_given_vnd INT NOT NULL,
  guest_name VARCHAR(120) NOT NULL DEFAULT '',
  handled_by INT NULL,
  handled_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_currency_log_date (log_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS company_accounts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  contact_name VARCHAR(120) NOT NULL DEFAULT '',
  contact_email VARCHAR(160) NOT NULL DEFAULT '',
  contact_phone VARCHAR(40) NOT NULL DEFAULT '',
  billing_details TEXT NOT NULL DEFAULT '',
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS company_transactions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  company_account_id INT NOT NULL,
  txn_date DATE NOT NULL,
  kind ENUM('charge', 'payment') NOT NULL,
  amount_vnd INT NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  folio_id INT NULL,
  folio_line_id INT NULL,
  invoice_id INT NULL,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_company_txns_account (company_account_id, txn_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS audit_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  created_at BIGINT NOT NULL,
  username VARCHAR(80) NOT NULL DEFAULT '',
  user_id INT NULL,
  action VARCHAR(60) NOT NULL,
  entity_type VARCHAR(40) NOT NULL DEFAULT '',
  entity_id INT NULL,
  detail VARCHAR(500) NOT NULL DEFAULT '',
  INDEX idx_audit_log_created (created_at),
  INDEX idx_audit_log_user (username, created_at),
  INDEX idx_audit_log_action (action, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Daily operations and revenue (v11). housekeeping_tasks is the
-- phone workflow: a task runs open, claimed, in progress, done,
-- inspected, with an SLA due time and photo proof stored as a data
-- URL in photo_data (capped server-side at 512,000 characters, so
-- no file storage is needed on shared hosting). Turnover tasks are
-- auto-created for dirty rooms. housekeeping_defects is the
-- maintenance list: an open defect puts the room out of order until
-- it is fixed. guests is one record per guest, created from
-- bookings; guest_merges records a merge with the moved booking and
-- folio ids, so it can be undone once. id_captures holds the self
-- check-in data (structured ID fields, ID photo and signature as
-- data URLs); it is only ever returned by the single-record ID
-- action, never in a list. groups and group_rooms are group
-- bookings and their rooming lists; a group taking all 7 rooms is a
-- whole-property buyout. pos_tables, pos_menu_items, pos_bills,
-- pos_bill_items and pos_bill_payments are the Ve Cafe POS: 8
-- tables, one open bill per table, items split across payers
-- numbered 1 to 9, payments by cash, card or room charge (a room
-- charge records the folio and line it posted to). rate_seasons,
-- rate_season_rooms, rate_plans, meal_plans, vouchers,
-- rate_guardrails and rate_rules are the rate engine: a season has
-- a multiplier percent, with per-room override rates in
-- rate_season_rooms; a plan adjusts the nightly rate by a
-- percentage; a meal plan adds an amount per person per night (or
-- per room per night when per_person is 0); a voucher is fixed VND
-- or a percentage, with validity dates and a use count; a
-- guardrail is a minimum and maximum nightly rate per room (either
-- may be NULL for no bound); a rule is a weekend, event-date or
-- occupancy-threshold adjustment, percent or fixed. report_budgets
-- holds monthly budget targets per line (rooms_revenue,
-- fb_revenue, other_revenue, expenses, gop); report_snapshots
-- holds one saved figures pack per month.
CREATE TABLE IF NOT EXISTS housekeeping_tasks (
  id INT AUTO_INCREMENT PRIMARY KEY,
  room_id INT NOT NULL,
  task_date DATE NOT NULL,
  kind ENUM('turnover', 'deep_clean', 'inspection') NOT NULL DEFAULT 'turnover',
  status ENUM('open', 'claimed', 'in_progress', 'done', 'inspected') NOT NULL DEFAULT 'open',
  sla_due_at BIGINT NULL,
  claimed_by INT NULL,
  claimed_by_name VARCHAR(80) NOT NULL DEFAULT '',
  started_at BIGINT NULL,
  finished_at BIGINT NULL,
  finished_by INT NULL,
  finished_by_name VARCHAR(80) NOT NULL DEFAULT '',
  photo_data MEDIUMTEXT NOT NULL DEFAULT '',
  inspected_by INT NULL,
  inspected_by_name VARCHAR(80) NOT NULL DEFAULT '',
  inspected_at BIGINT NULL,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_hk_tasks_room_date (room_id, task_date),
  INDEX idx_hk_tasks_status (status, sla_due_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS housekeeping_defects (
  id INT AUTO_INCREMENT PRIMARY KEY,
  room_id INT NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  photo_data MEDIUMTEXT NOT NULL DEFAULT '',
  status ENUM('open', 'fixed') NOT NULL DEFAULT 'open',
  reported_by INT NULL,
  reported_by_name VARCHAR(80) NOT NULL DEFAULT '',
  reported_at BIGINT NOT NULL,
  fixed_by INT NULL,
  fixed_by_name VARCHAR(80) NOT NULL DEFAULT '',
  fixed_at BIGINT NULL,
  created_at BIGINT NOT NULL,
  INDEX idx_hk_defects_room (room_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS guests (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(160) NOT NULL DEFAULT '',
  phone VARCHAR(40) NOT NULL DEFAULT '',
  vip TINYINT(1) NOT NULL DEFAULT 0,
  blacklisted TINYINT(1) NOT NULL DEFAULT 0,
  blacklist_reason VARCHAR(255) NOT NULL DEFAULT '',
  merged_into INT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_guests_email (email),
  INDEX idx_guests_phone (phone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS guest_merges (
  id INT AUTO_INCREMENT PRIMARY KEY,
  from_guest_id INT NOT NULL,
  to_guest_id INT NOT NULL,
  moved_booking_ids TEXT NOT NULL DEFAULT '',
  moved_folio_ids TEXT NOT NULL DEFAULT '',
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  undone TINYINT(1) NOT NULL DEFAULT 0,
  undone_at BIGINT NULL,
  undone_by INT NULL,
  undone_by_name VARCHAR(80) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS id_captures (
  id INT AUTO_INCREMENT PRIMARY KEY,
  booking_id INT NOT NULL UNIQUE,
  full_name VARCHAR(120) NOT NULL,
  id_type ENUM('passport', 'national_id', 'other') NOT NULL DEFAULT 'passport',
  id_number VARCHAR(60) NOT NULL DEFAULT '',
  nationality VARCHAR(60) NOT NULL DEFAULT '',
  date_of_birth DATE NULL,
  expiry_date DATE NULL,
  id_photo_data MEDIUMTEXT NOT NULL DEFAULT '',
  signature_data MEDIUMTEXT NOT NULL DEFAULT '',
  captured_by INT NULL,
  captured_by_name VARCHAR(80) NOT NULL DEFAULT '',
  captured_at BIGINT NOT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS groups (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  contact_name VARCHAR(120) NOT NULL DEFAULT '',
  contact_email VARCHAR(160) NOT NULL DEFAULT '',
  contact_phone VARCHAR(40) NOT NULL DEFAULT '',
  check_in DATE NOT NULL,
  check_out DATE NOT NULL,
  rate_type ENUM('per_room_night', 'flat_total') NOT NULL DEFAULT 'per_room_night',
  rate_vnd INT NOT NULL,
  deposit_vnd INT NOT NULL DEFAULT 0,
  deposit_due_date DATE NULL,
  deposit_paid TINYINT(1) NOT NULL DEFAULT 0,
  deposit_paid_at BIGINT NULL,
  status ENUM('quote', 'confirmed', 'cancelled') NOT NULL DEFAULT 'confirmed',
  notes TEXT NOT NULL DEFAULT '',
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS group_rooms (
  id INT AUTO_INCREMENT PRIMARY KEY,
  group_id INT NOT NULL,
  room_id INT NOT NULL,
  guest_name VARCHAR(120) NOT NULL DEFAULT '',
  booking_id INT NULL,
  created_at BIGINT NOT NULL,
  INDEX idx_group_rooms_group (group_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS pos_tables (
  id INT AUTO_INCREMENT PRIMARY KEY,
  table_number INT NOT NULL UNIQUE,
  name VARCHAR(40) NOT NULL DEFAULT '',
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS pos_menu_items (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name_en VARCHAR(120) NOT NULL,
  name_vi VARCHAR(120) NOT NULL DEFAULT '',
  category ENUM('food', 'beverage', 'other') NOT NULL DEFAULT 'other',
  price_vnd INT NOT NULL,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS pos_bills (
  id INT AUTO_INCREMENT PRIMARY KEY,
  table_id INT NOT NULL,
  status ENUM('open', 'closed', 'voided') NOT NULL DEFAULT 'open',
  opened_by INT NULL,
  opened_by_name VARCHAR(80) NOT NULL DEFAULT '',
  opened_at BIGINT NOT NULL,
  closed_at BIGINT NULL,
  closed_by INT NULL,
  closed_by_name VARCHAR(80) NOT NULL DEFAULT '',
  total_vnd INT NOT NULL DEFAULT 0,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_pos_bills_status (status, opened_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS pos_bill_items (
  id INT AUTO_INCREMENT PRIMARY KEY,
  bill_id INT NOT NULL,
  menu_item_id INT NULL,
  item_name_en VARCHAR(120) NOT NULL DEFAULT '',
  item_name_vi VARCHAR(120) NOT NULL DEFAULT '',
  category ENUM('food', 'beverage', 'other') NOT NULL DEFAULT 'other',
  unit_price_vnd INT NOT NULL,
  qty INT NOT NULL DEFAULT 1,
  status ENUM('ordered', 'done') NOT NULL DEFAULT 'ordered',
  payer INT NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_pos_bill_items_bill (bill_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS pos_bill_payments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  bill_id INT NOT NULL,
  payer INT NOT NULL DEFAULT 1,
  method ENUM('cash', 'card', 'room') NOT NULL,
  amount_vnd INT NOT NULL,
  room_id INT NULL,
  folio_id INT NULL,
  folio_line_id INT NULL,
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_pos_bill_payments_bill (bill_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_seasons (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  start_date DATE NOT NULL,
  end_date DATE NOT NULL,
  multiplier_percent INT NOT NULL DEFAULT 100,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_season_rooms (
  id INT AUTO_INCREMENT PRIMARY KEY,
  season_id INT NOT NULL,
  room_id INT NOT NULL,
  override_vnd INT NOT NULL,
  UNIQUE KEY ux_season_room (season_id, room_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_plans (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  adjustment_percent INT NOT NULL DEFAULT 0,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS meal_plans (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  description VARCHAR(255) NOT NULL DEFAULT '',
  addon_vnd INT NOT NULL DEFAULT 0,
  per_person TINYINT(1) NOT NULL DEFAULT 1,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS vouchers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  code VARCHAR(40) NOT NULL UNIQUE,
  kind ENUM('fixed', 'percent') NOT NULL DEFAULT 'fixed',
  value INT NOT NULL,
  valid_from DATE NULL,
  valid_to DATE NULL,
  max_uses INT NULL,
  uses INT NOT NULL DEFAULT 0,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_guardrails (
  id INT AUTO_INCREMENT PRIMARY KEY,
  room_id INT NOT NULL UNIQUE,
  min_vnd INT NULL,
  max_vnd INT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_rules (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  rule_type ENUM('weekend', 'event', 'occupancy') NOT NULL,
  event_start_date DATE NULL,
  event_end_date DATE NULL,
  occupancy_threshold INT NULL,
  adjustment_type ENUM('percent', 'fixed') NOT NULL DEFAULT 'percent',
  adjustment_value INT NOT NULL,
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS report_budgets (
  id INT AUTO_INCREMENT PRIMARY KEY,
  month VARCHAR(7) NOT NULL,
  line_key VARCHAR(40) NOT NULL,
  target_vnd INT NOT NULL,
  UNIQUE KEY ux_budget_month_line (month, line_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS report_snapshots (
  id INT AUTO_INCREMENT PRIMARY KEY,
  month VARCHAR(7) NOT NULL UNIQUE,
  snapshot_json TEXT NOT NULL DEFAULT '',
  created_by INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Connect and automate tables (v12, Phase 3). Sync integrity:
-- sync_revisions records every import outcome, reconciliation_runs
-- and reconciliation_diffs record provider comparisons. iCal push:
-- ical_push_tokens holds one token per room, ical_push_log records
-- feed requests. Automation: automation_rules and automation_runs,
-- plus notifications and ledger_notes. Messaging:
-- message_templates (4 keys x 3 channels), messaging_providers
-- (WhatsApp and Zalo), message_outbox, message_threads and
-- message_items. API tokens: api_tokens (SHA-256 hashes only).
-- Smart lock stub: smart_lock_providers and smart_lock_events.
-- Hotel-as-YAML config: config_snapshots. The server creates all
-- of these itself on startup, so they are here for a fresh schema
-- import only; an existing install never needs this file re-run.
CREATE TABLE IF NOT EXISTS sync_revisions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  connector_id INT NOT NULL,
  external_provider VARCHAR(40) NOT NULL,
  external_id VARCHAR(120) NOT NULL,
  booking_id INT NULL,
  revision_no INT NOT NULL,
  payload_json TEXT NOT NULL,
  change_type VARCHAR(20) NOT NULL,
  created_at BIGINT NOT NULL,
  INDEX idx_sync_revisions (connector_id, external_id, revision_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS reconciliation_runs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  connector_id INT NOT NULL,
  started_at BIGINT NOT NULL,
  finished_at BIGINT NULL,
  status ENUM('running', 'success', 'error') NOT NULL DEFAULT 'running',
  diffs_found INT NOT NULL DEFAULT 0,
  error TEXT NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS reconciliation_diffs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  run_id INT NOT NULL,
  connector_id INT NOT NULL,
  external_provider VARCHAR(40) NOT NULL,
  external_id VARCHAR(120) NOT NULL DEFAULT '',
  booking_id INT NULL,
  diff_type ENUM('missing_in_pms', 'missing_in_provider', 'field_diff', 'status_diff') NOT NULL,
  detail_json TEXT NOT NULL,
  status ENUM('open', 'resolved', 'ignored') NOT NULL DEFAULT 'open',
  created_at BIGINT NOT NULL,
  resolved_at BIGINT NULL,
  resolved_by_name VARCHAR(80) NOT NULL DEFAULT '',
  INDEX idx_recon_diffs_connector (connector_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ical_push_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  room_id INT NOT NULL UNIQUE,
  token VARCHAR(64) NOT NULL UNIQUE,
  created_at BIGINT NOT NULL,
  revoked_at BIGINT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ical_push_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  token_id INT NOT NULL,
  room_id INT NOT NULL,
  requested_at BIGINT NOT NULL,
  ip VARCHAR(45) NOT NULL DEFAULT '',
  user_agent VARCHAR(255) NOT NULL DEFAULT '',
  events_count INT NOT NULL DEFAULT 0,
  INDEX idx_ical_log_room (room_id, requested_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS automation_rules (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(120) NOT NULL,
  trigger_key VARCHAR(40) NOT NULL,
  conditions_json TEXT NOT NULL DEFAULT '{}',
  actions_json TEXT NOT NULL DEFAULT '[]',
  enabled TINYINT(1) NOT NULL DEFAULT 1,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS automation_runs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  rule_id INT NOT NULL,
  trigger_key VARCHAR(40) NOT NULL,
  entity_type VARCHAR(20) NOT NULL DEFAULT '',
  entity_id INT NULL,
  status ENUM('done', 'failed', 'skipped') NOT NULL DEFAULT 'done',
  detail_json TEXT NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_auto_runs_rule (rule_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS notifications (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(160) NOT NULL,
  body TEXT NOT NULL DEFAULT '',
  link_view VARCHAR(40) NOT NULL DEFAULT '',
  is_read TINYINT(1) NOT NULL DEFAULT 0,
  created_at BIGINT NOT NULL,
  INDEX idx_notifications_read (is_read, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ledger_notes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  note TEXT NOT NULL,
  amount_vnd INT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS message_templates (
  id INT AUTO_INCREMENT PRIMARY KEY,
  template_key VARCHAR(40) NOT NULL,
  channel ENUM('whatsapp', 'zalo', 'email') NOT NULL,
  body_en TEXT NOT NULL,
  body_vi TEXT NOT NULL,
  updated_at BIGINT NOT NULL,
  UNIQUE INDEX ux_template_key_channel (template_key, channel)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS messaging_providers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  provider_key VARCHAR(20) NOT NULL UNIQUE,
  status ENUM('not_connected', 'configured') NOT NULL DEFAULT 'not_connected',
  config_enc TEXT NOT NULL DEFAULT '',
  config_hint VARCHAR(16) NOT NULL DEFAULT '',
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS message_outbox (
  id INT AUTO_INCREMENT PRIMARY KEY,
  booking_id INT NULL,
  guest_id INT NULL,
  template_key VARCHAR(40) NOT NULL,
  channel ENUM('whatsapp', 'zalo', 'email') NOT NULL,
  recipient VARCHAR(160) NOT NULL DEFAULT '',
  body TEXT NOT NULL,
  status ENUM('queued', 'ready', 'sent', 'failed', 'cancelled') NOT NULL DEFAULT 'queued',
  error TEXT NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL,
  INDEX idx_outbox_status (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS message_threads (
  id INT AUTO_INCREMENT PRIMARY KEY,
  booking_id INT NULL,
  guest_id INT NULL,
  channel ENUM('whatsapp', 'zalo', 'email') NOT NULL,
  created_at BIGINT NOT NULL,
  last_message_at BIGINT NOT NULL,
  INDEX idx_threads_booking (booking_id, channel)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS message_items (
  id INT AUTO_INCREMENT PRIMARY KEY,
  thread_id INT NOT NULL,
  direction ENUM('in', 'out') NOT NULL,
  body TEXT NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_message_items_thread (thread_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS api_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80) NOT NULL,
  token_hash CHAR(64) NOT NULL UNIQUE,
  scopes_json TEXT NOT NULL,
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  last_used_at BIGINT NULL,
  revoked_at BIGINT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS smart_lock_providers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  provider_key VARCHAR(20) NOT NULL UNIQUE,
  status ENUM('not_connected', 'configured') NOT NULL DEFAULT 'not_connected',
  config_enc TEXT NOT NULL DEFAULT '',
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS smart_lock_events (
  id INT AUTO_INCREMENT PRIMARY KEY,
  booking_id INT NOT NULL,
  room_id INT NOT NULL,
  event ENUM('issue', 'activate', 'revoke', 'expire') NOT NULL,
  code_ref VARCHAR(20) NULL,
  provider_key VARCHAR(20) NOT NULL DEFAULT 'stub',
  status VARCHAR(20) NOT NULL DEFAULT 'no_provider',
  detail TEXT NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_lock_events_booking (booking_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS config_snapshots (
  id INT AUTO_INCREMENT PRIMARY KEY,
  snapshot_yaml MEDIUMTEXT NOT NULL,
  diff_json TEXT NOT NULL DEFAULT '',
  created_by_name VARCHAR(80) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Finish the hooks (v13, Phase 4). Scheduled report email
-- (email_schedules, email_send_log), receipt files for the ledger
-- (receipts), and the guest check-in link (checkin_tokens, plus
-- the pre_checked_in flag on bookings above). The server creates
-- these tables itself on startup, so a fresh install does not
-- need this file for them, and an existing install gains them on
-- its first v13 start with no phpMyAdmin step.
CREATE TABLE IF NOT EXISTS email_schedules (
  id INT AUTO_INCREMENT PRIMARY KEY,
  report_type ENUM('flash', 'snapshot') NOT NULL,
  frequency ENUM('weekly', 'monthly') NOT NULL,
  day_of_week INT NULL,
  day_of_month INT NULL,
  recipients TEXT NOT NULL,
  lang ENUM('en', 'vi') NOT NULL DEFAULT 'en',
  enabled TINYINT(1) NOT NULL DEFAULT 1,
  last_sent_at BIGINT NULL,
  created_at BIGINT NOT NULL,
  updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS email_send_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  schedule_id INT NULL,
  report_type VARCHAR(20) NOT NULL,
  recipients TEXT NOT NULL,
  subject VARCHAR(255) NOT NULL DEFAULT '',
  status ENUM('sent', 'failed') NOT NULL,
  error TEXT NOT NULL DEFAULT '',
  sent_at BIGINT NOT NULL,
  INDEX idx_email_log_sent (sent_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS receipts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  entry_kind ENUM('expense', 'revenue') NOT NULL,
  entry_id INT NOT NULL,
  file_name VARCHAR(64) NOT NULL,
  original_name VARCHAR(255) NOT NULL DEFAULT '',
  mime VARCHAR(60) NOT NULL DEFAULT '',
  size_bytes INT NOT NULL DEFAULT 0,
  uploaded_by INT NULL,
  uploaded_by_name VARCHAR(100) NOT NULL DEFAULT '',
  created_at BIGINT NOT NULL,
  INDEX idx_receipts_entry (entry_kind, entry_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS checkin_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  booking_id INT NOT NULL UNIQUE,
  token VARCHAR(64) NOT NULL UNIQUE,
  status ENUM('active', 'revoked', 'used', 'expired') NOT NULL DEFAULT 'active',
  created_at BIGINT NOT NULL,
  expires_at BIGINT NOT NULL,
  revoked_at BIGINT NULL,
  used_at BIGINT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Ve Cafe tables 1 to 8, the starter menu (a STARTER list to edit,
-- not a real Ve Cafe menu), the 3 meal plans (zero add-on, the admin
-- sets the price), and the Standard rate plan. INSERT IGNORE makes
-- re-importing this file safe, and the server seeds the same rows
-- itself when the tables are empty.
INSERT IGNORE INTO pos_tables (table_number, name, active, created_at) VALUES
  (1, 'Table 1', 1, 0),
  (2, 'Table 2', 1, 0),
  (3, 'Table 3', 1, 0),
  (4, 'Table 4', 1, 0),
  (5, 'Table 5', 1, 0),
  (6, 'Table 6', 1, 0),
  (7, 'Table 7', 1, 0),
  (8, 'Table 8', 1, 0);

INSERT IGNORE INTO pos_menu_items (name_en, name_vi, category, price_vnd, active, created_at, updated_at) VALUES
  ('Vietnamese coffee', 'Cà phê sữa đá', 'beverage', 35000, 1, 0, 0),
  ('Iced tea', 'Trà đá', 'beverage', 25000, 1, 0, 0),
  ('Orange juice', 'Nước cam', 'beverage', 45000, 1, 0, 0),
  ('Mineral water', 'Nước khoáng', 'beverage', 20000, 1, 0, 0),
  ('Beer', 'Bia', 'beverage', 40000, 1, 0, 0),
  ('Banh mi', 'Bánh mì', 'food', 55000, 1, 0, 0),
  ('Pho', 'Phở', 'food', 85000, 1, 0, 0),
  ('Spring rolls', 'Gỏi cuốn', 'food', 65000, 1, 0, 0);

INSERT IGNORE INTO meal_plans (name, description, addon_vnd, per_person, active, created_at, updated_at) VALUES
  ('Room only', 'No meals included.', 0, 1, 1, 0, 0),
  ('Breakfast included', 'Breakfast for each guest, each night. Set the price.', 0, 1, 1, 0, 0),
  ('Breakfast and dinner', 'Breakfast and dinner for each guest, each night. Set the price.', 0, 1, 1, 0, 0);

INSERT IGNORE INTO rate_plans (name, description, adjustment_percent, active, created_at, updated_at) VALUES
  ('Standard', 'The standard rate, no adjustment.', 0, 1, 0, 0);

-- The real Chon Boutique Stay inventory, as confirmed by the owner.
-- Floor 1 Sanctuary, floor 2 Vivid, floor 3 Euphoria, floor 4
-- Dreamscape, floor 5 Still, floor 6 Dune, floor 7 Blue.
-- Rates are per night, VAT included. Sanctuary 1,190,000 VND,
-- Vivid 1,790,000 VND, the other five 1,990,000 VND each.
-- INSERT IGNORE makes re-importing this file safe.
INSERT IGNORE INTO rooms (slug, name_en, name_vi, floor, rate_vnd, palette, balcony, housekeeping_status) VALUES
  ('sanctuary', 'Sanctuary', 'Chốn Tĩnh', 1, 1190000, '#c96f2e', 0, 'clean'),
  ('vivid', 'Vivid', 'Chốn Sắc', 2, 1790000, '#c2457e', 0, 'clean'),
  ('euphoria', 'Euphoria', 'Chốn Say', 3, 1990000, '#9e2233', 0, 'clean'),
  ('dreamscape', 'Dreamscape', 'Chốn Mơ', 4, 1990000, '#a8873f', 0, 'clean'),
  ('still', 'Still', 'Chốn Lặng', 5, 1990000, '#7d8471', 0, 'clean'),
  ('dune', 'Dune', 'Chốn Hoang', 6, 1990000, '#b4552d', 0, 'clean'),
  ('blue', 'Blue', 'Chốn Xanh', 7, 1990000, '#5b84a8', 1, 'clean');

-- The chonadmin admin account is NOT created by this file, on purpose,
-- so no password ever sits in a SQL file. The server creates chonadmin
-- on its first run, from the CHON_ADMIN_PASSWORD environment variable
-- you set in cPanel Setup Node.js App, hashed with PBKDF2 before it
-- is stored. If the variable is not set, no admin is created and the
-- login page tells you the platform is not set up yet.
