-- Cierre: Desglose + Verificacion de Pagos

-- 1) Add flags to payment config
ALTER TABLE phppos_cierre_config_pago
  ADD COLUMN enable_breakdown TINYINT(1) NOT NULL DEFAULT 0,
  ADD COLUMN include_in_verification TINYINT(1) NOT NULL DEFAULT 0;

-- 2) New action for verification page
INSERT IGNORE INTO phppos_modules_actions (action_id, module_id, action_name_key, sort) VALUES
('payment_verification','cierre','cierre_payment_verification',50);

INSERT IGNORE INTO phppos_permissions_actions (module_id, person_id, action_id) VALUES
('cierre',1,'payment_verification');

-- 3) Breakdown lines table (individual amounts)
CREATE TABLE IF NOT EXISTS phppos_cierre_payment_breakdown (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  cierre_id INT NOT NULL,
  cierre_detalle_id INT NOT NULL,
  amount DECIMAL(23,10) NOT NULL DEFAULT 0,
  verified TINYINT(1) NOT NULL DEFAULT 0,
  created_by_employee_id INT(10) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_cierre_detalle (cierre_detalle_id),
  KEY idx_cierre (cierre_id),
  KEY idx_verified (verified),
  CONSTRAINT fk_cpb_cierre FOREIGN KEY (cierre_id) REFERENCES phppos_cierres(id) ON DELETE CASCADE,
  CONSTRAINT fk_cpb_detalle FOREIGN KEY (cierre_detalle_id) REFERENCES phppos_cierre_detalle(id) ON DELETE CASCADE,
  CONSTRAINT fk_cpb_employee FOREIGN KEY (created_by_employee_id) REFERENCES phppos_employees(person_id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- 4) Verification table for payments WITHOUT breakdown (one line per detalle)
CREATE TABLE IF NOT EXISTS phppos_cierre_payment_verification (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  cierre_id INT NOT NULL,
  cierre_detalle_id INT NOT NULL,
  verified TINYINT(1) NOT NULL DEFAULT 0,
  verified_by_employee_id INT(10) NULL,
  verified_at DATETIME NULL,
  UNIQUE KEY uk_detalle (cierre_detalle_id),
  KEY idx_cierre (cierre_id),
  KEY idx_verified (verified),
  CONSTRAINT fk_cpv_cierre FOREIGN KEY (cierre_id) REFERENCES phppos_cierres(id) ON DELETE CASCADE,
  CONSTRAINT fk_cpv_detalle FOREIGN KEY (cierre_detalle_id) REFERENCES phppos_cierre_detalle(id) ON DELETE CASCADE,
  CONSTRAINT fk_cpv_employee FOREIGN KEY (verified_by_employee_id) REFERENCES phppos_employees(person_id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
