-- Fase 5: POS / caja / cobros
-- Ejecuta después de schema.sql y schema_phase4.sql

SET NAMES utf8mb4;

-- Productos (inventario simple con alerta de stock bajo)
CREATE TABLE IF NOT EXISTS products (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id  BIGINT UNSIGNED NOT NULL,
  name         VARCHAR(150) NOT NULL,
  sku          VARCHAR(60) NULL,
  price_cents  INT UNSIGNED NOT NULL DEFAULT 0,
  cost_cents   INT UNSIGNED NOT NULL DEFAULT 0,
  stock        INT NOT NULL DEFAULT 0,
  stock_min    INT NOT NULL DEFAULT 0,
  is_active    TINYINT(1) NOT NULL DEFAULT 1,
  created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (business_id),
  CONSTRAINT fk_prod_biz FOREIGN KEY (business_id) REFERENCES businesses(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Sesión / apertura de caja
CREATE TABLE IF NOT EXISTS cash_sessions (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id   BIGINT UNSIGNED NOT NULL,
  opened_by     BIGINT UNSIGNED NULL,
  opened_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  opening_cents INT NOT NULL DEFAULT 0,
  closed_at     DATETIME NULL,
  closing_cents INT NULL,               -- efectivo contado al cerrar
  expected_cents INT NULL,              -- calculado por el sistema
  diff_cents    INT NULL,               -- closing - expected
  notes         TEXT NULL,
  KEY (business_id, opened_at),
  CONSTRAINT fk_cash_biz FOREIGN KEY (business_id) REFERENCES businesses(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Ventas / tickets
CREATE TABLE IF NOT EXISTS sales (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id     BIGINT UNSIGNED NOT NULL,
  session_id      BIGINT UNSIGNED NULL,
  appointment_id  BIGINT UNSIGNED NULL,
  customer_id     BIGINT UNSIGNED NULL,
  staff_id        BIGINT UNSIGNED NULL,   -- staff que atendió (para comisiones)
  subtotal_cents  INT NOT NULL DEFAULT 0,
  discount_cents  INT NOT NULL DEFAULT 0,
  tip_cents       INT NOT NULL DEFAULT 0,
  total_cents     INT NOT NULL DEFAULT 0,
  paid_cents      INT NOT NULL DEFAULT 0,
  status          ENUM('open','paid','void') NOT NULL DEFAULT 'open',
  notes           TEXT NULL,
  created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  paid_at         DATETIME NULL,
  KEY (business_id, created_at),
  KEY (session_id),
  KEY (appointment_id),
  CONSTRAINT fk_sale_biz  FOREIGN KEY (business_id) REFERENCES businesses(id) ON DELETE CASCADE,
  CONSTRAINT fk_sale_sess FOREIGN KEY (session_id)  REFERENCES cash_sessions(id) ON DELETE SET NULL,
  CONSTRAINT fk_sale_app  FOREIGN KEY (appointment_id) REFERENCES appointments(id) ON DELETE SET NULL,
  CONSTRAINT fk_sale_cus  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE SET NULL,
  CONSTRAINT fk_sale_stf  FOREIGN KEY (staff_id)    REFERENCES staff(id)     ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Ítems de venta (servicio o producto)
CREATE TABLE IF NOT EXISTS sale_items (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  sale_id       BIGINT UNSIGNED NOT NULL,
  kind          ENUM('service','product','custom') NOT NULL,
  ref_id        BIGINT UNSIGNED NULL,     -- service_id o product_id
  staff_id      BIGINT UNSIGNED NULL,     -- quien lo realizó (comisión)
  name          VARCHAR(180) NOT NULL,
  qty           DECIMAL(10,2) NOT NULL DEFAULT 1,
  unit_cents    INT NOT NULL DEFAULT 0,
  total_cents   INT NOT NULL DEFAULT 0,
  commission_cents INT NOT NULL DEFAULT 0,
  KEY (sale_id),
  CONSTRAINT fk_it_sale FOREIGN KEY (sale_id) REFERENCES sales(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Pagos aplicados a una venta (permite pagos mixtos)
CREATE TABLE IF NOT EXISTS sale_payments (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  sale_id      BIGINT UNSIGNED NOT NULL,
  session_id   BIGINT UNSIGNED NULL,
  method       ENUM('cash','card','transfer','wompi','other') NOT NULL,
  amount_cents INT NOT NULL,
  reference    VARCHAR(120) NULL,
  created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (sale_id), KEY (session_id, method),
  CONSTRAINT fk_pmt_sale FOREIGN KEY (sale_id)    REFERENCES sales(id) ON DELETE CASCADE,
  CONSTRAINT fk_pmt_sess FOREIGN KEY (session_id) REFERENCES cash_sessions(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Movimientos manuales de caja (retiros / ingresos que no son ventas)
CREATE TABLE IF NOT EXISTS cash_movements (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  session_id   BIGINT UNSIGNED NOT NULL,
  business_id  BIGINT UNSIGNED NOT NULL,
  kind         ENUM('in','out') NOT NULL,
  amount_cents INT NOT NULL,
  reason       VARCHAR(200) NULL,
  created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (session_id),
  CONSTRAINT fk_mv_sess FOREIGN KEY (session_id)  REFERENCES cash_sessions(id) ON DELETE CASCADE,
  CONSTRAINT fk_mv_biz  FOREIGN KEY (business_id) REFERENCES businesses(id)   ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
