-- Fase 6: Nómina + anticipos / préstamos
-- Ejecuta después de schema_phase5.sql

SET NAMES utf8mb4;

-- Ampliaciones a staff
ALTER TABLE staff
  ADD COLUMN base_pay_cents INT NOT NULL DEFAULT 0 AFTER commission_pct,
  ADD COLUMN pay_frequency ENUM('weekly','biweekly','monthly') NOT NULL DEFAULT 'biweekly' AFTER base_pay_cents;

-- Anticipos y préstamos entregados al staff
CREATE TABLE IF NOT EXISTS staff_advances (
  id                BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id       BIGINT UNSIGNED NOT NULL,
  staff_id          BIGINT UNSIGNED NOT NULL,
  kind              ENUM('advance','loan') NOT NULL DEFAULT 'advance',
  amount_cents      INT NOT NULL,           -- total entregado
  remaining_cents   INT NOT NULL,           -- saldo pendiente por descontar
  installment_cents INT NOT NULL DEFAULT 0, -- cuota por liquidación (0 = todo de una)
  method            ENUM('cash','transfer','other') NOT NULL DEFAULT 'cash',
  session_id        BIGINT UNSIGNED NULL,   -- si sale de una caja abierta
  note              VARCHAR(255) NULL,
  status            ENUM('active','paid','cancelled') NOT NULL DEFAULT 'active',
  created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (business_id, staff_id, status),
  CONSTRAINT fk_adv_biz  FOREIGN KEY (business_id) REFERENCES businesses(id) ON DELETE CASCADE,
  CONSTRAINT fk_adv_stf  FOREIGN KEY (staff_id)    REFERENCES staff(id)      ON DELETE CASCADE,
  CONSTRAINT fk_adv_sess FOREIGN KEY (session_id)  REFERENCES cash_sessions(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Periodos de nómina liquidados por staff
CREATE TABLE IF NOT EXISTS payroll_periods (
  id                 BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id        BIGINT UNSIGNED NOT NULL,
  staff_id           BIGINT UNSIGNED NOT NULL,
  start_date         DATE NOT NULL,
  end_date           DATE NOT NULL,
  base_cents         INT NOT NULL DEFAULT 0,
  commission_cents   INT NOT NULL DEFAULT 0,
  tips_cents         INT NOT NULL DEFAULT 0,
  adjustments_cents  INT NOT NULL DEFAULT 0,  -- positivos o negativos
  deductions_cents   INT NOT NULL DEFAULT 0,  -- suma anticipos/préstamos descontados
  net_cents          INT NOT NULL DEFAULT 0,  -- total a pagar
  status             ENUM('draft','paid','void') NOT NULL DEFAULT 'draft',
  paid_at            DATETIME NULL,
  paid_method        ENUM('cash','transfer','other') NULL,
  session_id         BIGINT UNSIGNED NULL,
  notes              TEXT NULL,
  created_at         DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (business_id, staff_id, start_date),
  CONSTRAINT fk_pp_biz FOREIGN KEY (business_id) REFERENCES businesses(id) ON DELETE CASCADE,
  CONSTRAINT fk_pp_stf FOREIGN KEY (staff_id)    REFERENCES staff(id)      ON DELETE CASCADE,
  CONSTRAINT fk_pp_ses FOREIGN KEY (session_id)  REFERENCES cash_sessions(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Detalle: qué compone el periodo (comisiones por sale_item, propinas, ajustes, deducciones)
CREATE TABLE IF NOT EXISTS payroll_items (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  period_id      BIGINT UNSIGNED NOT NULL,
  kind           ENUM('base','commission','tip','adjustment','advance_deduction','loan_deduction') NOT NULL,
  ref_type       ENUM('sale_item','sale','advance','manual') NOT NULL DEFAULT 'manual',
  ref_id         BIGINT UNSIGNED NULL,
  description    VARCHAR(255) NULL,
  amount_cents   INT NOT NULL,   -- positivo = a favor; negativo = descuento
  created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (period_id),
  CONSTRAINT fk_pi_period FOREIGN KEY (period_id) REFERENCES payroll_periods(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Marcar sale_items ya liquidados (evita doble pago)
ALTER TABLE sale_items
  ADD COLUMN payroll_period_id BIGINT UNSIGNED NULL AFTER commission_cents,
  ADD KEY idx_si_payroll (payroll_period_id, staff_id),
  ADD CONSTRAINT fk_si_pp FOREIGN KEY (payroll_period_id) REFERENCES payroll_periods(id) ON DELETE SET NULL;
