USE peluqueria;

DELIMITER $$

DROP PROCEDURE IF EXISTS spu_caja_egreso_reg $$
CREATE PROCEDURE spu_caja_egreso_reg(
  IN p_suc_id INT,
  IN p_monto DECIMAL(12,2),
  IN p_observacion TEXT
)
BEGIN
  DECLARE v_caj_id INT DEFAULT NULL;

  SELECT caj_id
    INTO v_caj_id
  FROM caja
  WHERE suc_id = p_suc_id
    AND caj_estado = 'ABIERTA'
  ORDER BY caj_fecha DESC, caj_id DESC
  LIMIT 1;

  IF v_caj_id IS NULL THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Debe abrir caja antes de registrar egresos';
  END IF;

  INSERT INTO caja_movimientos(caj_id, cam_tipo, cam_monto, cam_observacion)
  VALUES(v_caj_id, 'EGRESO', p_monto, p_observacion);

  SELECT
    v_caj_id AS caj_id,
    LAST_INSERT_ID() AS cam_id,
    p_monto AS egreso,
    p_observacion AS observacion;
END $$

DELIMITER ;
